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

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


那如何才能在非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();
        }
    });
}




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。