从另一个线程更新Android UI的调用方法是否有效?

问题描述

我会给你两段代码。一种代码更新了子线程的UI。是的,您没听错我的声音!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".NbPlus">
    <TextView
        android:id="@+id/tv_test"
        android:text="TEXT"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:onClick="updateText"
        android:text="updateText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Java代码

public class NbPlus extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);
        textView = findViewById(R.id.tv_test);
    }

    public void updateText(View view) {
        System.out.println("NB PLUS");
        new Thread(() -> textView.setText("Click Me!!!")).start();
    }
}

现在您可以运行此代码,这太了不起了,它可以正常工作。 如果您能解释原因,请告诉我。

解决方法

这不是bug,但也不能保证能正常工作。 Android UI工具包API合同规定,必须在UI线程(几乎总是与主线程相同)上进行UI更新。如果您对setText的调用已经完成,那么如果您通过从另一个线程进行更新而违反了此规则,将会发生什么,则未定义。它可能会起作用,可能无效,可能会立即崩溃,或者可能会破坏事物和/或稍后崩溃。

通常会从错误的线程中错误调用的许多方法会显式检查它们所在的线程,如果不是UI线程则会崩溃。此功能旨在帮助开发人员更轻松地发现错误,而不是任何需要进行UI修改的方法行为。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...