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

在调试软件的时候出现如下的错误:

01-05 20:53:36.492: E/ZZShip(2043): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

又是一个ThreadException,之前也碰到过。

解决方法:

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {

  //这里可以做一些,比如关闭加载对话框

}

}

//--------------------------------------------------------------------

try {
new Thread(new Runnable() {
@Override
public void run() {
try {

//打开加载对话框
//与服务器进行通讯

mHandler.post(runnableUI);


} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}).start();
} catch (Exception e) {
Log.e(TAG, e.toString());
}

//--------------------------------------------------------------------

// 构建Runnable对象,在runnable中更新界面
Runnable runnableUI=new Runnable(){
@Override
public void run() {
  //更新UI

  mHandler.sendEmptyMessage(1);//更新完成以后,发送对话框关闭加载对话框
}
};

道法自然
原文地址:https://www.cnblogs.com/jiduoduo/p/4317424.html