android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

前言:昨天试着用okhttp来请求网络并显示数据,所以很不幸:

但是又很幸运,我很快找到了解决方法。

this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI

            }
        });

再来探究一下为什么这么做:

这个bug出现的原因是不能在子线程更新UI,UI线程不允许其它线程更新UI组件中的内容。
所以上述是一种通过子线程更新UI的方式。如果主类是Activity的话就可以(类名.this.runOnUiThread())。但是我这个是Fragment,所以要获取到Activity,
即this.getActivity(),然后再调用runOnUiThread()方法。

猜你喜欢

转载自www.cnblogs.com/dearnotes/p/12230801.html