Android Preventing Double Click On A Button

2019-01-03 08:04发布

What is the best way to prevent double clicks on a button in Android?

30条回答
欢心
2楼-- · 2019-01-03 08:14

You can use this method. By using post delay you can take care for double click events.

void debounceEffectForClick(View view) {

    view.setClickable(false);

    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            view.setClickable(true);

        }
    }, 500);
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-03 08:14

We could use the button just synchronized like:

@Override
public void onClick(final View view) {
    synchronized (view) {

        view.setEnabled(false);

        switch (view.getId()) {
            case R.id.id1:
                ...
                break;
            case R.id.id2:
                ...
                break;
                ...
        }

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, 1000);
    }
}

Good Luck)

查看更多
乱世女痞
4楼-- · 2019-01-03 08:15

Setting Clickable to false does not work on the first double click but subsequent double clicks are blocked. It is as though the loading click delegate the first time is slower and the second click is captured before the first completes.

        Button button = contentView.FindViewById<Button>(Resource.Id.buttonIssue);
        button.Clickable = false;
        IssueSelectedItems();
        button.Clickable = true;
查看更多
混吃等死
5楼-- · 2019-01-03 08:16

saving a last click time when clicking will prevent this problem.

i.e.

private long mLastClickTime = 0;

...

// inside onCreate or so:

findViewById(R.id.button).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // mis-clicking prevention, using threshold of 1000 ms
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        // do your magic here
    }
}
查看更多
别忘想泡老子
6楼-- · 2019-01-03 08:16

you can also use rx bindings by jake wharton to accomplish this. here is a sample that pads 2 seconds between successive clicks:

RxView.clicks(btnSave)
                .throttleFirst(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept( Object v) throws Exception {
//handle onclick event here
                });

//note: ignore the Object v in this case and i think always.

查看更多
唯我独甜
7楼-- · 2019-01-03 08:17

setEnabled(false) works perfectly for me.

The idea is I write { setEnabled(true); } in the beginning and just make it false on the first click of the button.

查看更多
登录 后发表回答