我从许多教程和在线资源中读到,我们无法从主线程之外的其他地方访问 UI 元素。我们可以使用处理程序、runOnUiThread 或 AsyncTask 来访问 UI 元素。但是,我对下面的代码有一个疑问。
public class MainActivity extends Activity {
ProgressBar progress;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) findViewById(R.id.progreeBar);
text = (TextView) findViewById(R.id.loading);
Thread thread = new Thread(new myThread());
thread.start();
}
public class myThread implements Runnable{
@Override
public void run() {
progress.setProgress(50);
text.setText("counter: "+50);
}
}
}
在上面的代码中,我可以从另一个线程访问 UI 元素,而无需使用任何处理程序、runOnUiThread 或 AsyncTask。我很好奇为什么我从主线程外部访问 UI 元素没有错误?
最佳答案
是的,您可以从其他线程更新 UI,但您应该避免这样做。因为根据 Android 文档
Andoid UI toolkit is not thread-safe
关于java - 是否可以从主线程以外的地方访问 UI 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41136094/