Android中更新UI的几种方式: 1. Activity 的 runOnUiThread() 2. Handler 的 post() 3. Handler 的 sendMessage() 4. View 的 post()
1 public class FiveActivity extends Activity { 2 3 private TextView textView; 4 5 private Handler handler = new Handler() { 6 public void handleMessage(android.os.Message msg) { 7 textView.setText("ok2"); 8 }; 9 }; 10 11 private void handle1() { 12 13 handler.post(new Runnable() { 14 15 @Override 16 public void run() { 17 // TODO Auto-generated method stub 18 textView.setText("ok1"); 19 } 20 }); 21 22 } 23 24 // 最常见的的 25 public void handle2() { 26 handler.sendEmptyMessage(1); 27 } 28 29 public void updateUI() { 30 runOnUiThread(new Runnable() { 31 32 @Override 33 public void run() { 34 // TODO Auto-generated method stub 35 textView.setText("ok3"); 36 } 37 }); 38 } 39 40 public void viewUI() { 41 textView.post(new Runnable() { 42 43 @Override 44 public void run() { 45 // TODO Auto-generated method stub 46 textView.setText("ok4"); 47 } 48 }); 49 } 50 51 @Override 52 protected void onCreate(Bundle savedInstanceState) { 53 // TODO Auto-generated method stub 54 super.onCreate(savedInstanceState); 55 setContentView(R.layout.five); 56 textView = (TextView) findViewById(R.id.textView1); 57 new Thread() { 58 public void run() { 59 try { 60 Thread.sleep(2000); 61 // handle1() 62 // handle2(); 63 // updateUI(); 64 viewUI(); 65 } catch (InterruptedException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 } 70 }.start(); 71 } 72 }
时间: 2024-10-11 00:33:14