My Android button color is blue. I want to change the button color to red for 5 seconds. After 5 seconds, I need to change the button color back to blue.
Here is my code
 new Handler().postDelayed(new Runnable() {
                public void run() {
                    eyesOnchkBtn.setBackgroundColor(Color.RED);
                }
            }, 5000);
            eyesOnchkBtn.setBackgroundColor(Color.BLUE); // It wont change the color button as normal
Hope the following code will help
eyesOnchkBtn.setBackgroundColor(Color.RED);
new CountDownTimer(5000, 50) {
        @Override
        public void onTick(long arg0) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onFinish() {
                        eyesOnchkBtn.setBackgroundColor(Color.BLUE);
                    }
    }.start();
Just change your code a bit,
 eyesOnchkBtn.setOnClickListener( new OnClickListener(){
 @Override
 public void onClick() {
 // set the color red first.
 eyesOnchkBtn.setBackgroundColor(Color.RED);
 // change to original after 5 secs.
 new Handler().postDelayed(new Runnable() {
                public void run() {
                    eyesOnchkBtn.setBackgroundColor(Color.BLUE);
                }
            }, 5000);
 }
});
Try this
Timer myTimer;
MyTimerTask myTask = new MyTimerTask();
        myTimer = new Timer();
        myTimer.schedule(myTask, 0, 3000);
class MyTimerTask extends TimerTask {
        public void run() {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                    //Your color change code here
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
//Stop the timer when you finish your job.
@Override
    public void onPause() {
        super.onPause();
        try {
            myTimer.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onStop() {
        super.onStop();
        try {
            myTimer.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With