android.view.ViewRootImpl$CalledFromWrongThreadException:
2016-07-26 15:43
441 查看
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
在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回调函数中调用更新界面显示的函数。
法2:利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。
在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回调函数中调用更新界面显示的函数。
/** * 启动线程用来刷新登录提示文字,N秒刷新一次 * */ private class FreshWordsThread extends Thread { @Override public void run() { try { mLoadingWords = "test"; mLoadhandler.sendEmptyMessage(REFRESH); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } //主线程中的handler class LoadHandler extends Handler { /** * 接受子线程传递的消息机制 */ @Override public void handleMessage(Message msg) { super.handleMessage(msg); int what = msg.what; Log.i(TAG, "Main handler message code: " + what); switch (what) { case REFRESH: { // 刷新页面的文字 mLoadingText.setText(mLoadingWords); break; } } } }
法2:利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。
FusionField.currentActivity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(FusionField.currentActivity, "Success", Toast.LENGTH_LONG).show(); } });
相关文章推荐
- Android基础——对话框集合
- 移动应用开发效率工具
- 新手使用Android Studio 获取SHA1 信息
- android组件 fragment 重叠现象解决思路
- Android Sensor框架简述(三)
- Android Material 之NavigationView和TextInputLayout的使用
- Android 实现双击退出的功能
- 企业移动应用开发基本知识树 (Android & iOS)
- 解决android启动黑白屏最简洁的方式 一行代码搞定
- 合理应用activity的生命周期优化程序内存
- androidcopy文件
- android检查sd卡是否可写
- android长度转单位
- Android签名生成keystore
- Android ActionBar的使用
- android开发中总会遇到的小问题【持续更新...】
- Android学习之路------VideoView
- Android 下拉刷新控件
- Android自定义view生命周期
- Android定制及替换launcher