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

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

Only the original thread that created a view hierarchy can touch its views.

那怎样才干在非UI线程中更细UI呢?

方法有非常多种。在这里主要介绍三种:


第一种:调用主线程mHandlerpost(Runnable r)方法。

        该方法中的Runnable对象会被会加入到mHandler所在线程的Message消息队列中,假设mHandler在主线程中则Runnable 对象中的run方法将会在主线程中运行。所以能够达到更新UI线程的目的。

提示:

        Handler另一个与之类似的方法postDelayed(Runnable r, long delayMillis),该方法会在进行指定delayMillis时间的延迟之后将runnable对象加入到mHandler所在的线程中。


例如以下方法:

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();
        }
    });
}


另外一种:通过handler向主线程发送消息的机制该更新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();	



原文地址:https://www.cnblogs.com/yfceshi/p/7371554.html