是否可以从主线程以外访问UI元素?
问题描述:
我从很多教程和在线资源中读到,我们无法从主线程以外访问UI元素。在哪里,我们可以使用处理程序runOnUiThread或AsyncTask访问UI元素。但是,在下面这段代码中,我对此有个疑问。是否可以从主线程以外访问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元素。他们可能不会更新你想要的方式。 – ryantxr
我没有发现任何东西,除了你**不应该**在后台线程上使用UI。 –
对不起,我没有得到你。问题是我仍在学习和构建我的概念。在这里,我很困惑,为什么我可以从主线程访问UI,而没有任何runOnUiThread,Handlers或AysncTasks –