首页 > 移动平台 > 详细

Android开之在非UI线程中更新UI

时间:2014-08-27 20:34:08      阅读:228      评论:0      收藏:0      [点我收藏+]

当在非UI线程中更新UI(程序界面)时会出现如下图所示的异常:

bubuko.com,布布扣

那如何才能在非UI线程中更细UI呢?

方法有很多种,在这里主要介绍两种:

第一种:在需要更新UI的代码行后加Looper.prepare();Looper.loop();两句话即可。如:

new Thread(){
	@Override
	public void run() {
		// TODO Auto-generated method stub
		txtRotation.setText("在非UI线程中更新UI!");	
		Looper.prepare();
		Looper.loop();	
	}
	
}.start();	

第二种:使用如下方法:

new Thread(){
	@Override
	public void run() {
		// TODO Auto-generated method stub
		showToastByRunnable(MainActivity.this, "", 3000);
	}
	
}.start();	
/**
 * 在非UI线程中使用Toast
 * @param context 上下文
 * @param text 用以显示的消息内容
 * @param duration 消息显示的时间
 * */
private void showToastByRunnable(final Context context, final CharSequence text, final int duration) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(context, text, duration).show();
        }
    });
}




Android开之在非UI线程中更新UI

原文:http://blog.csdn.net/fengyuzhengfan/article/details/38875727

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!