In my app targeted for Android 4.0.3, I used to have a Button working as a Switch. Clicking on the button was making its resource change (switch between Play/Pause) and some tasks were performing in the background. The particularity is that when the Button was pressed, I wanted the toggle to be unavailable for a short period of time (to prevent fast switching).
To do so, I created a thread that was waiting for X seconds, like this :
void blockButton(){
new Thread() {
public void run(){
try {
synchronized(this){
button_ready = false;
sleep(5000);
button_ready = true;
}
}
catch(InterruptedException ex){}
}
}.start();
}
}
and basically in my Activity/onClickListener
if(button_ready){
// Start background stuff
changeButtonResource();
button.setEnabled(false);
blockButton();
button.setEnabled(true);
}
So far so good, everything was runnin smooth. But I eventually wished to update it to a Switch. The code is pretty much the same (except for the onClickListener that turned into a OnCheckedChangeListener).
But now when I click the button once, clicking it again will allow changing its resource – yet the background task will not start (I tried it with a Vibrator and others already, it only changes the resource).
So I almost have the behaviour my Button used to have, but the resource gets messed up. Any idea would be more than welcome ! Thanks.
You don’t need to create another thread.
View.postDelayed(Runnable)gives you a much easier way to enable buttons (or do other UI actions) after a timeout. Your code should look something like this:Calling
removeCallbacksbefore yourFragmentorActivitygoes away is important to avoid concurrency problems caused by the user leaving during the disabled period. And after disabling the callback in that case, it’s important to make sure you don’t then get ‘stuck’ in the disabled state when the user comes back to yourFragmentorActivityand theViewrestores its saved state.