2016-12-14 77 views
0

我从很多教程和在线资源中读到,我们无法从主线程以外访问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); 
    } 
} 
} 

Code Output

在上面的代码中,我可以访问来自另一个线程的UI元素,而无需使用任何处理程序,runOnUiThread,或的AsyncTask。我很好奇,为什么我在访问主线程之外的UI元素时没有错误?

+0

您可以访问的UI元素。他们可能不会更新你想要的方式。 – ryantxr

+0

我没有发现任何东西,除了你**不应该**在后台线程上使用UI。 –

+0

对不起,我没有得到你。问题是我仍在学习和构建我的概念。在这里,我很困惑,为什么我可以从主线程访问UI,而没有任何runOnUiThread,Handlers或AysncTasks –

回答

1

是的,你可以从其他线程更新UI,但你应该避免它。因为按照Android文档

Andoid UI工具包是不是thread-safe

相关问题