'Delay handler inside a loop in android [duplicate]

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);
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1