发生android.view.ViewRoot$CalledFromWrongThreadException异常的解决方案(转载http://daydayup1989.iteye.com/blog/784831)

在Android平台下,进行多线程编程时,经常需要在主线程之外的一个单独的线程中进行某些处理,然后更新用户界面显示。但是,在主线线程之外的线程中直接更新页面显示的问题是

报异常:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

【只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)】

也就是说必须在一般必须在程序的主线程(也就是ui)线程中进行更新界面显示的工作。可以采用下面的方法之一来解决:

法1:

在Activity.onCreate(Bundle savedInstanceState)中创建一个Handler类的实例, 在这个Handler实例的handleMessage回调函数中调用更新界面显示的函数。

Java代码  收藏代码
  1.   /** 
  2.      * 启动线程用来刷新登录提示文字,N秒刷新一次 
  3.      *  
  4.      */  
  5.     private class FreshWordsThread extends Thread  
  6.     {  
  7.         @Override  
  8.         public void run()  
  9.         {  
  10.             try  
  11.             {  
  12.                 mLoadingWords = "test";  
  13.                 mLoadhandler.sendEmptyMessage(REFRESH);  
  14.             }  
  15.             catch (InterruptedException e)  
  16.             {  
  17.                 e.printStackTrace();  
  18.                 Thread.currentThread().interrupt();  
  19.             }  
  20.         }  
  21.     }  
  22.   
  23.   
  24.   
  25.     //主线程中的handler  
  26.     class LoadHandler extends Handler  
  27.     {  
  28.         /** 
  29.          * 接受子线程传递的消息机制 
  30.          */  
  31.         @Override  
  32.         public void handleMessage(Message msg)  
  33.         {  
  34.             super.handleMessage(msg);  
  35.             int what = msg.what;  
  36.   
  37.             Log.i(TAG, "Main handler message code: " + what);  
  38.             switch (what)  
  39.             {                  
  40.                 case REFRESH:  
  41.                 {  
  42.                     // 刷新页面的文字  
  43.                     mLoadingText.setText(mLoadingWords);  
  44.                     break;  
  45.                 }  
  46.   
  47.             }  
  48.         }  
  49.         
  50.     }  

法2:利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。

Java代码  收藏代码
  1. FusionField.currentActivity.runOnUiThread(new Runnable()  
  2.         {  
  3.             public void run()  
  4.             {  
  5.                 Toast.makeText(FusionField.currentActivity, "Success",  
  6.                         Toast.LENGTH_LONG).show();  
  7.             }  
  8.   
  9.         });  
原文地址:https://www.cnblogs.com/fuyanan/p/3992849.html