[关闭]
@Yano 2016-01-03T18:11:25.000000Z 字数 712 阅读 2473

Android 子线程更新 UI

Android


功能:每秒使 TextView 显示内容 +1。

  1. public class MainActivity extends Activity {
  2. private TextView textView;
  3. private Handler handler;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. textView = (TextView) findViewById(R.id.textView);
  9. handler = new Handler() {
  10. @Override
  11. public void handleMessage(Message msg) {
  12. super.handleMessage(msg);
  13. textView.setText((String) msg.obj);
  14. }
  15. };
  16. new Thread(new thread()).start();
  17. }
  18. // 每秒更新textview
  19. public class thread implements Runnable {
  20. public void run() {
  21. int c = 0;
  22. while (true) {
  23. try {
  24. Thread.sleep(1000);
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. // 将要更新的内容发给handler
  29. Message msg = new Message();
  30. msg.obj = "" + (c++);
  31. handler.sendMessage(msg);
  32. }
  33. }
  34. }
  35. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注