Handler用法
handler :更新UI的机制,消息的处理机制
四种用法sendMessage、sendMessageDelayed、post(runnable)、postDelayed(Runnable,long)
post用法
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用法
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(); } });