Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

android - No error calling textView.setText from non UI-Thread. Why?

I wrote the following Code which basically starts a Thread from which the text of a TextView is changed.

I was expecting an error because I access a TextTiew (UI-element) from another Thread than the main-Thread.

But it works fine. Thought this shouldn't be possible as far as I know.
I don't get it, what am I missing?

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv = (TextView) findViewById(R.id.view1);
        tv.setText(Thread.currentThread().getName());

        Thread theThread = new Thread(new aRunnable(tv));
        theThread.start();      
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

public class ARunnable implements Runnable{     
    TextView tv;    
    public ARunnable(TextView tv){
        this.tv = tv;
    }   
    @Override
    public void run() {
        tv.setText(tv.getText()+"----" + Thread.currentThread().getName()); 
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The docs say Do not access the Android UI toolkit from outside the UI thread. They do not say that Android itself contains any code to prevent you from doing so. It is merely a Bad Idea that could have unintended side effects.

You should call Activity.runOnUiThread() to update the UI from other threads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...