简体   繁体   中英

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

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();
        }
    }
button.setBackgroundColor(Color.GREEN);
button.postDelayed(new Runnable() {

  @Override
  public void run() {
    button.setBackgroundColor(Color.BLUE);
  }
}, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM