handler是什么?
handler是android给我们提供用来更新UI的一套机制,也是一套消息处理的机制,我们可以发送消息,也可以通过他处理消息。
为什么要用handler?
Android在设计的时候,就封装了一套消息创建,传递,处理机制,如果不遵循这样的机制,就没有办法更新UI消息了,就会抛出异常消息。
handler用法(一)
代码示例:
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
new Thread(){
public void run() {
try {
Thread.sleep(1000);
//更新文本信息
tv.setText("update Thread");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
异常原因:只能在原线程中更新UI
利用Handler更新UI,可以执行成功
public class MainActivity extends Activity {
private TextView tv;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
new Thread(){
public void run() {
try {
Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//更新文本信息
tv.setText("update Thread");
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
利用handrle做一个图片轮询的示例:
public class MainActivity extends Activity {
private TextView tv;
private ImageView img;
private Handler handler = new Handler();
private int images[] = {R.drawable.one,R.drawable.two,R.drawable.three};
private int index;
private MyRunnable myRunnable= new MyRunnable();
class MyRunnable implements Runnable{
/**
* TODO 简单描述该重写方法的实现功能(可选).
* @author Administrator 2014-12-25
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
index ++;
index = index%3;
img.setImageResource(images[index]);
handler.postDelayed(myRunnable, 1000);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1);
handler.postDelayed(myRunnable, 1000);
}
}