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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…