handler :更新UI的機制,消息的處理機制java
四種用法sendMessage、sendMessageDelayed、post(runnable)、postDelayed(Runnable,long)android
post用法ide
private android.os.Handler handler = new android.os.Handler(); new Thread() { public void run() { try { Thread.sleep(1000); handler.post(new Runnable() { @Override public void run() { text.setText("123"); } }); } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
sendMessage用法post
private android.os.Handler handler = new android.os.Handler() { @Override public void handleMessage(Message msg) { text.setText("" + msg.arg1); } }; new Thread() { @Override public void run() { try { Thread.sleep(1000); Message message = new Message(); message.arg1 = 100;
//handler.sendMessage(XXX);對象能夠是int,也能夠是obj對象
//message.obj=Person; Person是一個實體類對象 handler.sendMessage(message); } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
加上一個本身寫的頁面自動滑動的demo , 不是最正確的,只是能夠用的。對象
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: textView.setText("11111"); break; case 2: textView.setText("22222"); break; default: textView.setText("33333"); break; } } };
button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { for (int i = 1; i < 10000; i++) { try { Message message = new Message(); message.what = i % 3; handler.sendMessageDelayed(message, 1000); sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } }.start(); } });