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


当前回答

如果按钮做的唯一一件事是启动一个新活动,这个问题可以通过“singleTop”活动启动模式和在意图上设置FLAG_ACTIVITY_CLEAR_TOP来解决。这种方法不适用于复杂活动的层次结构,但适用于简单的树状应用程序结构。

其他回答

加上Jim的回答,代码可以变得更简洁:

fun View.setOnSingleClick(onClick: () -> Unit) {
    var lastClickTime = 0L
    setOnClickListener {
        if (currentTimeMillis() > lastClickTime + 750) onClick()
        lastClickTime = currentTimeMillis()
    } 
}

用法:

aView.setOnSingleClick {  }

对我来说,只有记住时间戳并检查它(距离上次点击超过1秒)才有帮助。

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

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

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).

如果你不想(或不能)使用布尔标志或覆盖onClickListener,你也可以尝试用android:launchMode="singleTop"在AndroidManifest.xml声明你的活动。

它是如何工作的?

如果活动的实例位于堆栈顶部- new activity不会被创建,相反- onNewIntent()将被调用。 活动可以有多个实例 实例可以驻留在不同的任务中 一个任务可以有多个实例