import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView; public class TestActivity extends Activity {
private TextView tv;
// 1 .创建出来handler 要求必须在主线程里面创建
private Handler handler = new Handler() {
// 主线程处理消息 调用的方法
@Override
public void handleMessage(Message msg) {
int count = (Integer) msg.obj;
tv.setText("当前条目为 " + count);
super.handleMessage(msg);
}
}; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.tv); // 每隔2秒钟更新一下 tv的内容
new Thread() { @Override
public void run() {
for (int i = 0; i < 100; i++) {
/* tv.setText("当前为"+ i); */
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = new Message();
msg.obj = i;
handler.sendMessage(msg);
}
super.run();
}
}.start(); }
}