Android onOptionsItemSelected avoid double click

2k views Asked by At

How to avoid double click on my example, any solutions?

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.testing) {
                Dialog();
    return super.onOptionsItemSelected(item);
}
3

There are 3 answers

2
Amsheer On BEST ANSWER

There is many way to achieve this. I am telling only sample example.

Just create a boolean variable in Activity class.

Boolean isClicked = false;

and then

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.testing) {
    if (!isClicked){
//Change here as your flag is true
isClicked = true;
                    Dialog();
    }
        return super.onOptionsItemSelected(item);
    }

Then this dialog shows only one time. If any changes needed ask.

1
John Joe On

Another easy approach is similar with @AlexV, use increment operator

Create a global variable

private var saveClickCounter: Int = 0

In onOptionsItemSelected

val id = item.itemId
    if (id == R.id.save)
    {
        if (saveClickCounter == 0) {
            Log.d(TAG, "clickedd")
            saveClickCounter++
        } else {
            Log.d(TAG, "OMG! U R fast!");
        }
    }
0
AlexV On

Sadly, but nothing from below options worked for me..

  1. Disabling view clicability - appeared to be too slow for "MAD CLICKER"
  2. setting some boolean (like isClicked to true) on click and checking it in onClickListener - looks fast, but not enough

Finally got a method which prevents "mad double click behaviour" on Menu items, which is even worse than double click on simple button, imo.

// define Fragment / Activity variable

volatile private byte saveClickCounter = 0;

// implement

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {            
        case R.id.common_action_save:

            if (saveClickCounter++ == 0) {
                saveButtonClick();
            } else {
                Log.i(TAG, "OMG! U R fast!");
            }

            return true;
    }

    return super.onOptionsItemSelected(item);
}

Don't forget to make that variable equal to zero again (or decrease that), after successfull method call.

saveClickCounter--;