非UI线程下更新view会崩溃
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
private TextView txtContent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txtContent = findViewById(R.id.txt_content);
new LooperThread("helloheloo").start();
}
private class LooperThread extends Thread {
private String text;
public LooperThread(String text) {
this.text = text;
}
@Override
public void run() {
super.run();
Thread.currentThread().setName("otherThread");
txtContent.setText(text);
}
}
这样不会崩溃
onCreate内调用setText(),界面不可见,不会调用invalidate方法,更不会调用checkThread(),所以不会崩溃,其实此时的setText方法并没有实现更新view操作。
本文探讨了在Android中非UI线程下更新View可能导致的崩溃问题。通过示例代码展示,在非创建View的原始线程中直接修改View属性会抛出CalledFromWrongThreadException异常。并给出了一种避免崩溃的方法:在View尚未初始化完成时进行操作。
1354

被折叠的 条评论
为什么被折叠?



