How to Pause or Sleep on Android

Asked 2 years ago, Updated 2 years ago, 99 views

I'd like to give you a short delay between the two lines. to explain When the user clicks the button, I want to change the background of the button and show it to the original background in a second.

thisbutton.setBackgroundResource(R.drawable.icon); When you click the button

thisbutton.setBackgroundResource(R.drawable.defaultcard); 1 second later

That's how it's supposed to stop the ad

try {
    Thread.sleep(1000);
} } catch (InterruptedException e) {
    // // TODO Auto-generated catch block
    e.printStackTrace();
}

I inserted a code like this between the two lines up there, but it doesn't work properly.

new Reminder(5);


public class Reminder {

Timer timer;

        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        }

        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                timer.cancel(); //Terminate the timer thread
            }
        }  
    }

I tried it like this, but as expected, it's not moving. What should I do?

multithreading android process

2022-09-21 17:08

1 Answers

It can be easily solved by using Handler's postDelayed method.

@Override
public void onClick(View v) {
    my_button.setBackgroundResource(R.drawable.icon);

    // If you want me to stop for two seconds, 
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 
              my_button.setBackgroundResource(R.drawable.defaultcard); 
         } 
    }, 2000); // 2000 means 2 seconds. 
}


2022-09-21 17:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.