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

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

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

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

            }
        });

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

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

相关文章:

  • 2021-11-09
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-18
  • 2022-01-09
  • 2021-07-12
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案