2010-2-14 关键词:Android Handler
如下的代码实现一个Iphone 上的一个通过按backspace键后,数字过多消除的按钮事件。事件的原理如下,事件要的效果是这样的,当长按消除按钮后,数字会慢慢消除,当消除5个字符后继续消除的话消除速度会增快。通过这份代码可以帮助我们较好的初识Handler的工作机制。 <!--more--> package com.william.handlertest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HandlerTest extends Activity implements Runnable{

private EditText content = null;
private Button backspace = null;

private boolean isStop = false;
private Handler mHandler = null;

private class BackspaceOnTouchListener implements Button.OnTouchListener{

@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
isStop = true;
mHandler = getHandler(content);
new Thread(HandlerTest. this).start();
break;
case MotionEvent.ACTION_UP:
isStop = false;
break;
default:
break;
}
return false;
}

}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

content = (EditText) findViewById(R.id.content);
content.setCursorVisible(false);

backspace = (Button) findViewById(R.id.backspace);
backspace.setOnTouchListener( new BackspaceOnTouchListener());
}

private Handler getHandler( final TextView content){
return new Handler(){

@Override
public void handleMessage(Message msg) {
content.setText((String)msg.obj);
super.handleMessage(msg);
}

};
}

@Override
public void run() {
try{
int i = 0;

do{

i++;
Thread.sleep((i > 5 ? 100 : 500));

String contentStr = this.content.getText().toString();
if(contentStr.length()==0){
break;
}
contentStr = contentStr.substring(0, contentStr.length()-1);

Message msg = mHandler.obtainMessage();
msg.obj=contentStr;
msg.sendToTarget();

} while(isStop);

} catch(Exception e){
e.printStackTrace();
}
}

} 代码参考了如下博文,在其消除至无字符时异常退出的非完美代码上进行了修改。 http://www.cnblogs.com/TerryBlog/archive/2010/08/25/1808445.html

通过Wiz发布

更多相关文章

  1. Kotlin&Anko, 扔掉XML开发Android应用
  2. ANE 在 Android(安卓)上的应用
  3. 深入浅出RxJava——在Android中使用响应式编程
  4. android之NDK环境小试牛刀
  5. phoneGap插件 .
  6. 【android】应用架构一一一一一Activity和Fragment的对比分析
  7. Android(安卓)Intent的几种用法全面总结
  8. Android(安卓)完美退出 App 方法
  9. android 中设置http请求头headers的Cookie

随机推荐

  1. android 之摄像头
  2. Android支付宝接口集成
  3. mac 下安装 android apk
  4. RelativeLayout常用属性
  5. Android基本组件
  6. Android(安卓)Studio第一章Big task1 - E
  7. android计算器布局界面——基础编
  8. shape.gradient使用示例
  9. Android判断手机是否是小米MIUI系统
  10. Android(安卓)Architecture