1

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){
                }
            }
}
guipivoto
  • 18,327
  • 9
  • 60
  • 75
newman
  • 149
  • 10

2 Answers2

3

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

Vincent
  • 2,073
  • 1
  • 17
  • 24
2

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).

A S M Sayem
  • 2,010
  • 2
  • 21
  • 28