ANDROID: How to set a delay after pressing a button?

I have a button, and when it is pressed, it plays an audio file. I want to put a 5-second delay on the button so that users do not overwrite the button and play the sound again and again. I think that I really want the button to be disabled within 5 seconds after pressing it. Does anyone know how to do this?

+7
source share
3 answers

In your onClickListener for the button:

myButton.setEnabled(false); Timer buttonTimer = new Timer(); buttonTimer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { myButton.setEnabled(true); } }); } }, 5000); 

This will turn off the button when pressed and turn it back on after 5 seconds.

If the click event is handled in a class that extends the view, and not in Activity, do the same, but replace runOnUiThread with post .

+29
source

You can turn off your button and then use postDelayed on your button.

 myButton.setEnabled(false); myButton.postDelayed(new Runnable() { @Override public void run() { myButton.setEnabled(true); } }, 5000); 

This is similar to the Timer solution, but may be better able to deal with a configuration change (for example, if the user turns the phone)

+19
source

Here you go.

 ((Button) findViewById(R.id.click)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ((Button) findViewById(R.id.click)).setEnabled(false); new Handler().postDelayed(new Runnable() { @Override public void run() { ((Button) findViewById(R.id.click)) .setEnabled(true); } }, 5000); } }); 
+2
source

All Articles