I have a problem with an app i’m currently making for Android phones. I have an Activity that has two Buttons. The point is if i press both buttons fast enough (that’s not a good user behaviour), those two buttons fire, while i want just to fire (at very most) only one of them. This a code fragment to example what I mean:
public class ActivityLevels extends Activity {
private boolean launched;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the content view of the screen
setContentView(R.layout.levels);
//Set lauched flag to false
launched = false;
//Initialize buttons
Button loadLevel01 = (Button) findViewById(R.id.ButtonLoadLevel01);
Button loadLevel02 = (Button) findViewById(R.id.ButtonLoadLevel02);
//Set Button Listeners
loadLevel01.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
launchGame(0);
}
});
loadLevel02.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
launchGame(1);
}
});
}
private void launchGame(int level) {
//Just launch the activity if !lanched
if(!launched) {
launched = true;
//Start Activity
}
}
}
I’ve been checking the internet for a week or so, and didn’t find any approach to prevent this. As far as i’ve discovered, looks like that someone has already posted a similar issue here: Issue 20073: Button onClick listener can be fired twice even if button is disabled immediately in listener
Btw, i’ve also tryed to disable the button just immediately before the “launchGame(int)” call, but not achieved anything.
This code is just an adapted fragment of the whole activity. I think that’s ok to understand what i mean, but if you need any other description, please let me know.
Thanks in advance, and sorry for any spelling mistakes, my english is not very good at all.
I actually solved my question. The point was to make my method
launchGame(int level)sychronized, so it can’t be accessed more than once before it finishes. This way, let’s say we have two threads from click listeners, because i pressed the button one and button two very very quick: with a synchronized method, it will be calledlauchGame(1), finish the action, and thenlaunchGame(2)with theboolean launchedflag setted totrue.This is what i’ve done:
Anyways, many thanks for all of your answers!