码迷,mamicode.com
首页 > 移动开发 > 详细

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

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

标签:only the original th   在非ui线程中更新ui   android在新线程中更新ui   在timer中更新ui   

当在非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

标签:only the original th   在非ui线程中更新ui   android在新线程中更新ui   在timer中更新ui   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!