To avoid multiple button click at same time

Bottleneck

Sometimes user can made bottleneck in your app when user click multiple button click at same time. you can avoid, it’s very easy.

To avoid multiple button clik at same time

The standard way to avoid multiple clicks is to save the last clicked time and avoid the other button clicks within 1 second(or any time span).

public class MainActivity extends Activity implements View.OnClickListener{

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonRight = (Button) findViewById(R.id.btnRight_activity_main);
        buttonLeft = (Button) findViewById(R.id.btnLeft_activity_main);

        buttonLeft.setOnClickListener(this);
        buttonRight.setOnClickListener(this);
    }

    // variable to track event time
    private long mLastClickTime = 0;

    @Override
    public void onClick(View v) {
        // Preventing multiple clicks, using threshold of 1 second
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
           return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();
        pressedOnClick(v);
    }

    public void pressedOnClick(View v){
        switch (v.getId()){
            case R.id.btnLeft_activity_main:
                showToast("Left_activity_main");
                break;

            case R.id.btnRight_activity_main:
                showToast("Right_activity_main");
                break;
        }

    }
}

example in github

3 thoughts on “To avoid multiple button click at same time

Leave a Reply

Your email address will not be published. Required fields are marked *