Fajar Khan Fajar Khan - 2 months ago 7
Android Question

Changing colour of a View every second within a time limit

I Have a

View
and i want change
BackgroundColor
of the view within a time limit. Lets say i want change the colour of the
View
to Red and Green every sec for a 20 min.

What i already tried:

final static int INTERVAL = 10000; // 1 second
private static View myView = null;
boolean whichColor = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (View) findViewById(R.id.my_view);
myView.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor();
whichColor = !whichColor;
}
}
}).start();
}

private void updateColor() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (whichColor)
myView.setBackgroundColor(Color.RED);
else
myView.setBackgroundColor(Color.GREEN);
}
});
}
}


This is changing colour of view every second but i want change only for a time limit. Is there any way i can do this?
Any help would be appreciated.

Answer

You have to just keep reference to the counter inside Runnable:

new Thread(new Runnable() {
    private static final int MAX_COUNT = 20 * 60;
    int counter = 0;

    public void run() {
        while (true) {
            if (counter >= MAX_COUNT) {
                break;
            }

            try {
                Thread.sleep(INTERVAL);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            counter++;
            updateColor();
            whichColor = !whichColor;
        }
    }
}).start();

Alternative:

Use Handler class and it's messages system.

Create class that extends Handler:

public class BlinkingHandler extends Handler {
    private static final int MAX_COUNT = 20 * 60;
    int counter = 0;

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == 123) {
            counter++;
            //Change background color
            if (counter < MAX_COUNT) {
                this.sendEmptyMessageDelayed(123, DateUtils.SECOND_IN_MILLIS);
            }
        }
    }
}

Init your Handler:

BlinkingHandler handler = new BlinkingHandler();
handler.sendEmptyMessage(123);