Reputation: 163
I'm a beginner in Android.
I made a simple code where I want to display a sequence of "hello 1", "hello 2"..."hello 5" in a textView with the step of 1 sec. However,every time only the last "hello 5" appears. Can anyone help me to modify my code to show in the textView all the intermediate words changing each other with 1-sec pause (from "hello 1" to "hello 5").
Thank you in advance!
View.OnClickListener onClickListener_button1 = new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=1; i<= 5; i++){
textView.setText("hello " + i);
try{Thread.sleep(1000);
} catch(Exception e){
}
}
}
Upvotes: 1
Views: 85
Reputation: 2093
The code is actually working and changing the content of your field from: hello 1 to hello 2 to hello 3 etc. You only do not have a chance to see it since the UI is not updated.
The problem with your code is that you use Thread.Sleep() which will block the (UI) thread so only the last hello 5 will be shown when the UI is not frozen anymore.
Take a look at this post for an alternative:
Wait some seconds without blocking UI execution
Upvotes: 3
Reputation: 2080
Use this code:
for (int i=1; i<6; i++) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText("hello " + i);
}
}, 1000);
}
Hope it will work (logically).
Upvotes: 2