在安卓系统中防止双击按钮的最佳方法是什么?


当前回答

下面的代码将防止用户点击多次在几分之一秒内,只允许3秒后。

private long lastClickTime = 0;

View.OnClickListener buttonHandler = new View.OnClickListener() {
    public void onClick(View v) {
        // preventing double, using threshold of 3000 ms
        if (SystemClock.elapsedRealtime() - lastClickTime < 3000){
            return;
        }

        lastClickTime = SystemClock.elapsedRealtime();
    }
}

其他回答

Setting the button as clickable false upon clicking and true once it is desired to make the button clickable again is the right approach. For instance, consider the following scenario: you are making a service call upon click of a button and once the service is done you want to display a dialog. For this, once the button is clicked you can set setClickable(false) and once the service responds you will do setClicklable(true) through a reference you pass to your custom dialog. When dialog invokes isShowing() you can trigger the listener and setClicklable(true).

试试这个Kotlin扩展函数:

private var lastClickTime = 0L

fun View.click(action: () -> Unit) {
    setOnClickListener {
        if (SystemClock.elapsedRealtime() - lastClickTime < 600L)
            return@setOnClickListener
        lastClickTime = SystemClock.elapsedRealtime()
        action()
    }
}

它还防止在同一时间点击应用程序的各个部分。

在点击的时候保存最后一次点击的时间可以避免这个问题。

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
    }
}

将Clickable设置为false对第一次双击不起作用,但后续双击将被阻止。这就好像第一次加载点击委托比较慢,第二次点击在第一次完成之前就被捕获了。

        Button button = contentView.FindViewById<Button>(Resource.Id.buttonIssue);
        button.Clickable = false;
        IssueSelectedItems();
        button.Clickable = true;

这个问题的实际解决方案是使用setEnabled(false),灰色按钮,和setClickable(false),使它第二次点击不能接收,我已经测试过了,它似乎是非常有效的。