32、handler更新控件值

 1 import android.app.Activity;  2 import android.os.Bundle;  3 import android.os.Handler;  4 import android.os.Message;  5 import android.widget.TextView;  6  7 public class TestActivity extends Activity {  8 private TextView tv;  9 // 1 .创建出来handler 要求必须在主线程里面创建 10 private Handler handler = new Handler() { 11 // 主线程处理消息 调用的方法 12  @Override 13 public void handleMessage(Message msg) { 14 int count = (Integer) msg.obj; 15 tv.setText("当前条目为 " + count); 16 super.handleMessage(msg); 17  } 18  }; 19 20  @Override 21 public void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23  setContentView(R.layout.main); 24 tv = (TextView) this.findViewById(R.id.tv); 25 26 // 每隔2秒钟更新一下 tv的内容 27 new Thread() { 28 29  @Override 30 public void run() { 31 for (int i = 0; i < 100; i++) { 32 /* tv.setText("当前为"+ i); */ 33 try { 34 sleep(500); 35 } catch (InterruptedException e) { 36  e.printStackTrace(); 37  } 38 Message msg = new Message(); 39 msg.obj = i; 40  handler.sendMessage(msg); 41  } 42 super.run(); 43  } 44  }.start(); 45 46  } 47 }

 

你可能感兴趣的:(handler)