-1

I tried to print a message that is changing in a textwiew. The problem when I did this is that the app is waiting the end of the loop to put the result.

public class Testloop extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testloop);
        String message = "test : ";
        for(int x = 1; x < 20; x = x + 1) {
             message +=x;
             int timeInMills = 1000; // time in ms
             SystemClock.sleep(timeInMills);
             TextView textView = (TextView) findViewById(R.id.txte);
             textView.setText(message);
        }
}
Boken
  • 4,825
  • 10
  • 32
  • 42

1 Answers1

0

The onCreate method is not a good place for this. The loop will finish before the activity is even visible, and the last string you set will be the only one displayed. Try using a Runnable with a Handler, like this:

private Handler handler = new Handler();
handler.postDelayed(runnable, 100);

That will tell the runnable to run in 100ms. Then create the runnable like this:

private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      //Set your text here
      textView.setText(message);
      // here you set the runnable to run again in 100ms
      handler.postDelayed(this, 100);
   }
};

Put your message strings in an array and index through it each time the runnable runs.

Jason Powell
  • 361
  • 4
  • 12