How to resolve double tap on Button Issue in android?

Darshak picture Darshak · May 21, 2013 · Viewed 14.7k times · Source

Mockup of my Application :

Double Tap Mockup


Problem :

When click on button1 it just call Intent of ActivitySecond

button1.setOnClickListener(this);

public void onClick(View v) {
// TODO Auto-generated method stub
     switch (v.getId()) 
     {
          case R.id.button1:
                Intent intent = new Intent(getApplicationContext(), ActivitySecond.class);
                startActivity(intent);
                break;
          default:
                break;
     }
}

But, on Double tap it open twice ActivitySecond.


HOW TO RESOLVE IT.

PLEASE IF ANY SOLUTION THEN SHARE IT.

Thank you.

Answer

Yaroslav Buhaiev picture Yaroslav Buhaiev · Dec 26, 2013

As Gabe Sechan sad:

This can be done via timer (get the time they click on it, save it, and if they click it again within say 100ms ignore the 2nd click)

Here is an implementation that i used in my project:

public abstract class OnOneClickListener implements View.OnClickListener {
    private static final long MIN_CLICK_INTERVAL = 1000; //in millis
    private long lastClickTime = 0;

    @Override
    public final void onClick(View v) {
        long currentTime = SystemClock.elapsedRealtime();
        if (currentTime - lastClickTime > MIN_CLICK_INTERVAL) {
            lastClickTime = currentTime;
            onOneClick(v);
        }
    }

    public abstract void onOneClick(View v);
}

Just use OnOneClickListener instead of OnClickListener and execute your code in onOneClick() method.

The solution with disabling button in onClick() will not work. Two clicks on a button can be scheduled for execution even before your first onClick() will execute and disable the button.