How to prevent double code running by clicking twice fast to a button in Android

Adam Varhegyi picture Adam Varhegyi · Jul 2, 2012 · Viewed 8.1k times · Source

If i click fast to my button in my Android app, it seems that code behind it runs twice. If i click my menu button twice the activity that has to be launch onclick just starts twice and i have to quit from it twice.

This is really annoying because if i click too fast for menu buttons i can load up a whole bunch of activities in the background and i must quit them one by one, so this is clearly a buggy state of my app i want to fix this.

What can i do with this issue?

I use simple onClickListeners and Buttons

EDIT:

Regarding to answers and comments my menu buttons look like this:

top20Button.setOnClickListener(new OnClickListener()
{
    public void onClick(View v)
    {
        favButton.setClickable(false);
        nearButton.setClickable(false);
        highlightedButton.setClickable(false);
        top20Button.setClickable(false);

        Intent i = new Intent();
        i.putExtra("showDialog", false);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        i.setClass(Search.this, Top20.class);
        startActivity(i);
        finish();

    }
});

After all this correction its still the same :S When i click like a mad person multiple activites are on the history stack and i must quit multiple times.

Any suggestions ? What m i doing wrong?

Answer

Shrikant picture Shrikant · Jul 2, 2012

You can use following code: btn.setEnabled(false);

btn.setOnclickListener(new View.onClickListener(){

      public void onClick(View v) {
            btn.setEnabled(false);

      }
});