-1

I am trying to insert the handler to the loop but it makes it happen only once.

for(int i = 0;i<4;i++) {
    btn1.setBackgroundColor(Color.RED);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            btn1.setBackgroundColor(Color.GREEN);
        }
    }, 2000);
}
ATP
  • 2,939
  • 4
  • 13
  • 34

1 Answers1

0

If you want the button to change between red and green with a delay of 2 seconds you can try something like this:

for(int i = 0;i<4;i++) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btn1.setBackgroundColor(Color.RED);
                    }
    }, 2000*2*i);
    new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        btn1.setBackgroundColor(Color.GREEN);
                    }
    }, 2000*(2*i+1));
}

When using

new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    btn1.setBackgroundColor(Color.GREEN);
                }
            }, 2000)

you set the delay to a fixed value. to make the button blink the delay has to be dynamic and changed every loop iteration.

ATP
  • 2,939
  • 4
  • 13
  • 34