Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to change the color of a button for a few seconds than change it back

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
like image 496
Seetha Avatar asked Sep 10 '13 07:09

Seetha


3 Answers

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();
like image 110
Anu Avatar answered Oct 07 '22 00:10

Anu


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);
 }
});
like image 36
Rachit Mishra Avatar answered Oct 06 '22 23:10

Rachit Mishra


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();
        }
    }
like image 34
Pratik Dasa Avatar answered Oct 07 '22 01:10

Pratik Dasa