Handler更新主线程UI常用方法

来源:互联网 发布:网络恐怖主义事件 编辑:程序博客网 时间:2024/05/16 09:52

   Handler对我们从事安卓开发的程序猿来说是再熟悉不过了。它是Android提供更新主线程 UI的一种机制,对过它可以发消息,收消息及处理消息,实现UI更新等操作。Android设计时就已经确实了不能在子线程中直接更新主线程UI,所以我们在开发的时候要严格按照相关机制来处理。

/**
 * 
 * @description:通过Handler实现更新UI中TextView文字显示
 * @date 2015-11-30 上午9:03:18
 */

public class MainActivity extends Activity {

private TextView test_tv;
private Handler mHandler = new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test_tv = (TextView) findViewById(R.id.test_tv);
new Thread() {
@Override
public void run() {
try {
sleep(2000);
//test_tv.setText("更新UI数据");如果直接这样写,不用Handler则肯定会报错,提示不能在非UI线程直接更新
mHandler.post(new Runnable() {
@Override
public void run() {
test_tv.setText("更新UI数据");
}
});
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}

----------------------------------------

/**
 * 
 * @description:通过Handler实现定时器,实现图片的轮播
 * 当然现在通常做法是用ViewFlipper或是ViewPager来实现
 * @date 2015-11-30 上午9:03:18
 */
public class MainActivity extends Activity {
private ImageView test_iv;
private Handler mHandler = new Handler();
private int[] imgIds ={ R.drawable.test_img_01, R.drawable.test_img_02, R.drawable.test_img_03 };
private int currentIndex;// 当前图片的位置
private MyRunable myRunable = new MyRunable();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test_iv = (ImageView) findViewById(R.id.test_iv);
mHandler.postDelayed(myRunable, 1000);
}


class MyRunable implements Runnable {


@Override
public void run() {
currentIndex++;
currentIndex = currentIndex % imgIds.length;
test_iv.setImageResource(imgIds[currentIndex]);
mHandler.postDelayed(this, 1000);
}

}
}

--------------------------------------------------------------

/**
 * 
 * @description:通过Handler发送消息及消息处理
 * @date 2015-11-30 上午10:15:46
 */
public class MainActivity extends Activity {
private TextView test_tv;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
// test_tv.setText("收到的消息为"+msg.arg1+"--"+msg.arg2);
test_tv.setText("收到的消息对象为"+msg.obj);
};
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test_tv = (TextView) findViewById(R.id.test_tv);
new Thread() {
public void run() {
try {
sleep(3000);// 模拟耗时操作
Message msg = new Message();
// msg.arg1 = 100;
// msg.arg2 = 200;
// mHandler.sendMessage(msg);
//发送对象数据
Student stu=new Student();
stu.setName("billy");
stu.setAge(30);
stu.setLevel(5);
msg.obj=stu;
mHandler.sendMessage(msg);
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}


}

------------Handler中移出消息-----------------------------------------------------

mHandler.removeCallback(runable);//传入对应的runable对象即可

0 0
原创粉丝点击