In the Android framework, if a TextView
's setText()
method is called, and after it returns Thead.sleep()
is called, then the screen of the device does not display the given text until after sleep()
has returned. Why?
public class SleeperActivity extends Activity {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
}
public void doDelay(View view) {
try {
TextView textView = (TextView) view;
textView.setText("Sleeping");
Log.d("Sleeper", "This log entry is invoked before sleeping");
Thread.sleep(5000L);
textView.setText("Ready");
} catch (InterruptedException e) { finish(); }
}
}
The layout, not shown, has a button whose onClick
attribute is set to doDelay()
.
When the above code is compiled and run, and the button is clicked, the text passed in the first invocation of setText()
does not appear on the screen until after the thread has slept for five seconds, even though the log entry appears in the log before those five seconds begin to elapse.
Why does this happen, and what ought I to do about it to make the text passed in the first call to setText()
appear on the screen before the thread begins to sleep?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…