简体   繁体   中英

Is it possible to access UI elements from other than the Main thread?

I have read from many tutorials and online resources that we can not access UI elements from other than the main threads. Where, we can access UI elements using handlers, runOnUiThread or AsyncTask. But, here I have a question regarding this from the following piece of code.

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);
    }
}
}

代码输出

In the above code, I can access the UI elements from another thread without using any handler, runOnUiThread, or AsyncTask. I am curious that why I have no error on accessing UI elements from outside the Main Thread?

Yes you can update UI from other thread but you should avoid it. Because as per Android documentation

Andoid UI toolkit is not thread-safe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM