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


当前回答

结合Gustavo的答案,我已经在Kotlin中实现了看起来非常干净的扩展:

fun View.setOnSingleClickListener(l: () -> Unit) {
  setOnClickListener { view ->
    l.invoke(view)
      isEnabled = false
      postDelayed({
        isEnabled = true
      }, 600)
  }
}

这是你如何设置这个点击监听器:

yourView.setOnSingleClickListener {
  // Insert your code 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()将被调用。 活动可以有多个实例 实例可以驻留在不同的任务中 一个任务可以有多个实例

使用setEnabled(false)禁用按钮,直到用户可以安全地再次单击它。

试试这个,它是有效的:

mButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

                mSlotLayout.setEnabled(false);

        //      do your work here

                Timer buttonTimer = new Timer();
                buttonTimer.schedule(new TimerTask() {

                    @Override
                    public void run() {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                mButton.setEnabled(true);
                            }
                        });
                    }
                }, 500); // delay button enable for 0.5 sec
    }
});

如果有人还在寻找一个简短的答案,你可以使用下面的代码

 private static long mLastClickTime = 0;
  if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) { // 1000 = 1second
         return;
    }
 mLastClickTime = SystemClock.elapsedRealtime();

当用户在1秒内单击View时,这段代码将进入if语句,然后返回;将被启动,而进一步的代码将不会被启动。