Activity 创建过程(子线程更新 UI 真的可以吗)

来看个都遇到过的 Error

相信大家都遇到过这种 Exception 吧

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

只有主线程能更新 UI,但是子线程真的不能更新 UI 吗?我们来看以下代码

片段一: onCreate 中开启子线程来更新 UI


public class StartActivity extends AppCompatActivity {

    private TextView tvName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        tvName = findViewById(R.id.tv_name);

        new Thread(() -> {
            tvName.setText("Hello, WhenSun!");
        }).start();
    }
}
复制代码

很简单的代码,绑定控件之后直接在子线程更新TextView显示的内容为 Hello, WhenSun!,来猜下是否能运行呢?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享