解决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
在这里插入图片描述
翻译过来就是:只有创建view层次结构的原始线程才能操作它的view

出现原因:回调接口在子线程,并在回调接口对UI进行了操作

所以,将会出现上述提示

一般来讲,会使用handle解决这个问题

在对应的回调接口根据网络请求返回的数据来传递不同的消息

handler.sendMessage(msg);

再根据消息的内容执行进一步操作

private Handler handler = new Handler()
{
    
    
    @Override
    public void handleMessage(Message msg) {
    
    
        super.handleMessage(msg);
        switch (msg.what)
        {
    
    
            case 1:
                ...
                break;
        }
    }
};

另外还有一种解决方案很省事

直接使用runOnUiThread()

不过用多了对代码会显得不太清爽

MainActivity.this.runOnUiThread(new Runnable() {
    
    
    public void run() {
    
    
        ...
    }
});

如果是fragment:

getActivity.runOnUiThread(new Runnable() {
    
    
            public void run() {
    
    
                ...
            }
        });

猜你喜欢

转载自blog.csdn.net/i_nclude/article/details/105563688