CalledFromWrongThreadException: Only the original thread that created a view
2014-06-13 16:05
369 查看
初遇这问题,不知道因为啥,所以问了一下度娘,知道了这句英文的意思:只能在原来的线程中创建view。实际上就是只能在主线程上创建view,或对UI进行更新,可是还是不 明白,因为我是在主线程中更新的啊,后来经过せんせい的指导,终于发现了问题,因为我更新UI是在回调接口里面,而回调是写在一个子线程里面,这才明白了错误的原因,而 且明白了:在子线程中执行回调函数,虽然跳出了子线程,但之后的操作任然属于子线程!
既然明白了为题所在,就要解决问题了,
要想控制主线程改变view,必须得以主线程的身份。如何让主线程知道要改变它呢,就要用到Handler类了。
之后在回调函数的调用方及主线程中调用mHandler让主线程View做出改变
还有一种Android独有的方法runOnUiThread ,它也能在线程中执行UI更新操作。
实现如下:
既然明白了为题所在,就要解决问题了,
要想控制主线程改变view,必须得以主线程的身份。如何让主线程知道要改变它呢,就要用到Handler类了。
private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { name.setText(msg.obj.toString()); }; };
之后在回调函数的调用方及主线程中调用mHandler让主线程View做出改变
Message message = new Message(); message.obj = user.uName; mHandler.sendMessage(message);
还有一种Android独有的方法runOnUiThread ,它也能在线程中执行UI更新操作。
实现如下:
runOnUiThread(new Runnable() { @Override public void run() { name.setText(user.uName); } });
相关文章推荐
- android ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hi
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- CalledFromWrongThreadException: Only the original thread that created a view
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view
- ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy
- CalledFromWrongThreadException:Only the original thread that created a view hierarchy can touch its
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a v
- calledfromwrongthreadexception only the original that created a view hierarchy can touch its views
- android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view h
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- 16-07-24 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original
- Android异常:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original
- 子线程中处理UI,抛异常 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original