`
tudusi
  • 浏览: 1048325 次
文章分类
社区版块
存档分类
最新评论

Android编程中,发生android.view.ViewRoot$CalledFromWrongThreadException异常的解决方案

 
阅读更多

在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回调函数中调用更新界面显示的函数。例如:

  view plaincopy to clipboardprint?

  public class ExampleActivity extends Activity {

  Handler h = null;

  @Override

  public void onCreate(Bundle savedInstanceState){

  h = new Handler(){

  @Override

  public void handleMessage(Message msg){

  // call updateGui method.

  }

  };

  }

  }

  public class ExampleActivity extends Activity {

  Handler h = null;

  @Override

  public void onCreate(Bundle savedInstanceState){

  h = new Handler(){

  @Override

  public void handleMessage(Message msg){

  // call updateGui method.

  }

  };

  }

  }

  在其它的函数中,利用 send族或post族函数向这个h发送或邮寄消息即可。

  解决方案2:利用Activity.runOnUiThread(Runnable)

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

http://www.cnmsdn.com/html/201009/1284080180ID7930.html

分享到:
评论

相关推荐

    问题:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original

    问题:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a 我的场景是 LinearLayout.LayoutParams params11 = new LinearLayout.LayoutParams(264, LinearLayout....

    开新线程引发的常见3个异常

    2.android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 3.java.lang.RuntimeException: Can't create handler inside thread ...

    Android实现在子线程中更新Activity中UI的方法

    本文实例讲述了Android实现在子线程中更新Activity中...ERROR/AndroidRuntime(1222): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its

    详解Android UI更新的几种方法

    如果是在WT进行UI的更新,则会抛出异常,android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.(只有创建这个View的原

    Android 子线程更新UI

    android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 这个异常为何不是 Only the main thread that created a view hierarchy ...

    【Android】CalledFromWrongThreadException 深入源码分析

    先上结论 出现此问题的原因是:在非 UI 线程中创建了 Dialog,而在 UI 线程中调用了 show() 方法 问题还原 在使用 dialog 的时候,因为线程问题,在调用 dismiss() 方法...Caused by: android.view.ViewRootImpl$Called

    为什么能在子线程通过setText进行更新UI

    为什么可以在子线程通过setText进行更新UI ... Only the original thread that created a view hierarchy can touch its views.); } } 一般情况下在子线程更新UI是会报错的,因为在ViewRootImpl

Global site tag (gtag.js) - Google Analytics