首页 > 代码库 > "Only the original thread that created a view hierarchy can touch its views."解决

"Only the original thread that created a view hierarchy can touch its views."解决

  Android系统中的视图组件并不是线程安全的,如果要更新视图,必须在主线程中更新,不可以在子线程中执行更新的操作。所以可以依靠消息机制来进行更新。

  先声明一个handler来处理消息

 private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {                setContentView(child);        }    };

  然后在视图中触发的事件的方法中发送消息到handler来触发更新视图

        b2 = (Button) findViewById(R.id.return_button);        b2.setOnClickListener(new Button.OnClickListener() {            public void onClick(View v) {                setWebView();            }        });    

  

    private void setWebView() {        Message msg = new Message();        msg.what = CHANGE_WEB;        handler.sendMessage(msg);    }

  这样子就可以实现在其他线程中操作主视图。

 

"Only the original thread that created a view hierarchy can touch its views."解决