-1

today i started to write a simple android aplication. The idea is that method "click(View v)" witch is called when the button is pressed, will change background of a TextField to random color after 1 second for let's say 30 times

(long story short: 30 different background colors changing in 1 second intervals).

Here is what i have:

public void click(View v) {

    for(int i = 0; i >= 30; i++){       
       Random rand = new Random();
       final int red = rand.nextInt(255);
       final int green = rand.nextInt(255);
       final int blue = rand.nextInt(255);
       final TextView tf = (TextView) findViewById(R.id.textView1);

       // SLEEP 1 SECOND HERE ...
       Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
           public void run() {
            tf.setBackgroundColor(Color.rgb(red, green, blue));
           }
        }, 1000);   
    }
}

But when i press the button nothing happens. As a beginner, I would be very grateful for any advices how to fixs this.

2 Answers2

0

Try calling tf.invalidate() to force it to redraw.

Also if you want it to update every second for 30 seconds you should change the 1000 to i * 1000 (instead of sleeping as implied by comment). As currently written all the postDelayed end at about the same time.

You could also move the creation of handler outside of loop, no need to create multiples.

Finn K
  • 620
  • 3
  • 8
  • 1
    Thanks for the improvemenents, but unfortunately tf.invalidate() doesnt work for me. However, when I delete the for loop it works fine(on Button press background color changes after 1 sec., once.) – user3578760 May 02 '14 at 19:48
0

After 3 hours I finally solved this. There is a mistake in the for loop header. Exactly at i>=30. Written like this, the code in loop never starts. It has to be i<=30 . What a stupid mistake -_-

So the code look like this now:

public void click(View v) {
    Handler handler = new Handler();
    final Random rand = new Random();
    for(int i=1; i <= 30; i++){         
        handler.postDelayed(new Runnable() {
            public void run() {
                int red = rand.nextInt(255);
                int green = rand.nextInt(255);
                int blue = rand.nextInt(255);
                TextView tf = (TextView) findViewById(R.id.textView1);
                tf.setBackgroundColor(Color.rgb(red, green, blue));                 
            }
        }, i * 1000);                   
    }       
}

And it's working!