'Avoid an item from Action Bar from being double clicked

I have designed an action bar for my Android app. In this action bar there's a button that launches a Dialog Activity used to configure my app's behavior. If I double click this button fast enough, I'm able to order the Dialog Activity to be launched twice before it actually appears, and then it appears duplicated and visually overlapped and I don't want this. I tried to create some sort of lock-down mechanism but it is not working because my Dialog Activity is launched only after all the code in my Main Activity calling method (onOptionsItemSelected) is executed. Is there a way to avoid this form happening?

My code is:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

//ensure only one element from the option menu is launched at once (if you double click fast you could launch two)

Log.e("test", "onOptionsItemSelected ");
if(optionItemAlreadySelected == false)
{
    optionItemAlreadySelected = true;

    int id = item.getItemId();

    if (id ==  R.id.action_sound_mode) {
        //item.setVisible(false);
        Intent intent = new Intent(this, SoundConfigurationActivity.class);

        startActivity(intent);

        optionItemAlreadySelected = false; //this code is executed before the activity is started!!!
        return true;
    }

}

return super.onOptionsItemSelected(item);
}

Is there a way to know when the Dialog Activity has already being closed and lock the opportunity to open it once again until then.



Solution 1:[1]

Kotlin

It's a screen(Activity, Fragment) based solution to avoid a double tap on menu action.

  • Add below global variable to your activity/fragment containing onOptionsItemSelected function.

    private var previousClickTimeMillis = 0L
    
  • Write below function anywhere in the project i.e Utils.

    fun singleSafeClick(
    previousClickTimeMillis: Long,
    block: (previousClickTimeMillis: Long) -> Unit) {
    val currentTimeMillis = System.currentTimeMillis()
    if (currentTimeMillis < previousClickTimeMillis || currentTimeMillis >= previousClickTimeMillis + OnSingleClickListener.DELAY_MILLIS) {
     block(currentTimeMillis)
     }
    }
    
  • Write your triggering code as below.

     override fun onOptionsItemSelected(item: MenuItem): Boolean {
    
     when (item.itemId) {
         R.id.action_delete -> {
             singleSafeClick(previousClickTimeMillis) { tappedTime ->
                 previousClickTimeMillis = tappedTime
                // Write Yyur code here
             }
         }
     }
    }
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Maqsood