99

我的应用程序有一个问题,如果用户快速多次单击按钮,那么在我按住按钮的对话框消失之前会生成多个事件

我知道一个解决方案,方法是在单击按钮时将布尔变量设置为标志,这样可以防止将来的单击,直到对话框关闭。但是,我有很多按钮,并且每次都必须为每个按钮都这样做似乎是一种矫枉过正。android(或者可能是一些更智能的解决方案)中没有其他方法只允许每次单击按钮生成的事件操作吗?

更糟糕的是,在处理第一个动作之前,多次快速点击似乎会生成多个事件动作,所以如果我想在第一次点击处理方法中禁用按钮,队列中已经存在等待处理的事件动作!

请帮忙谢谢

4

20 回答 20

120

这是我最近写的一个“去抖动”的 onClick 监听器。你告诉它两次点击之间可接受的最小毫秒数是多少。实现你的逻辑onDebouncedClick而不是onClick

import android.os.SystemClock;
import android.view.View;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * A Debounced OnClickListener
 * Rejects clicks that are too close together in time.
 * This class is safe to use as an OnClickListener for multiple views, and will debounce each one separately.
 */
public abstract class DebouncedOnClickListener implements View.OnClickListener {

    private final long minimumIntervalMillis;
    private Map<View, Long> lastClickMap;

    /**
     * Implement this in your subclass instead of onClick
     * @param v The view that was clicked
     */
    public abstract void onDebouncedClick(View v);

    /**
     * The one and only constructor
     * @param minimumIntervalMillis The minimum allowed time between clicks - any click sooner than this after a previous click will be rejected
     */
    public DebouncedOnClickListener(long minimumIntervalMillis) {
        this.minimumIntervalMillis = minimumIntervalMillis;
        this.lastClickMap = new WeakHashMap<>();
    }

    @Override 
    public void onClick(View clickedView) {
        Long previousClickTimestamp = lastClickMap.get(clickedView);
        long currentTimestamp = SystemClock.uptimeMillis();

        lastClickMap.put(clickedView, currentTimestamp);
        if(previousClickTimestamp == null || Math.abs(currentTimestamp - previousClickTimestamp) > minimumIntervalMillis) {
            onDebouncedClick(clickedView);
        }
    }
}
于 2013-05-14T03:08:13.737 回答
75

使用RxBinding可以轻松完成。这是一个例子:

RxView.clicks(view).throttleFirst(500, TimeUnit.MILLISECONDS).subscribe(empty -> {
            // action on click
        });

添加以下行build.gradle以添加 RxBinding 依赖项:

compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
于 2016-02-29T17:09:02.283 回答
25

我们可以在没有任何库的情况下做到这一点。只需创建一个扩展函数:

fun View.clickWithDebounce(debounceTime: Long = 600L, action: () -> Unit) {
    this.setOnClickListener(object : View.OnClickListener {
        private var lastClickTime: Long = 0

        override fun onClick(v: View) {
            if (SystemClock.elapsedRealtime() - lastClickTime < debounceTime) return
            else action()

            lastClickTime = SystemClock.elapsedRealtime()
        }
    })
}

使用以下代码查看 onClick:

buttonShare.clickWithDebounce { 
   // Do anything you want
}
于 2019-06-05T14:27:23.153 回答
23

这是我接受的答案的版本。它非常相似,但不会尝试将视图存储在地图中,我认为这不是一个好主意。它还添加了一个在许多情况下可能有用的 wrap 方法。

/**
 * Implementation of {@link OnClickListener} that ignores subsequent clicks that happen too quickly after the first one.<br/>
 * To use this class, implement {@link #onSingleClick(View)} instead of {@link OnClickListener#onClick(View)}.
 */
public abstract class OnSingleClickListener implements OnClickListener {
    private static final String TAG = OnSingleClickListener.class.getSimpleName();

    private static final long MIN_DELAY_MS = 500;

    private long mLastClickTime;

    @Override
    public final void onClick(View v) {
        long lastClickTime = mLastClickTime;
        long now = System.currentTimeMillis();
        mLastClickTime = now;
        if (now - lastClickTime < MIN_DELAY_MS) {
            // Too fast: ignore
            if (Config.LOGD) Log.d(TAG, "onClick Clicked too quickly: ignored");
        } else {
            // Register the click
            onSingleClick(v);
        }
    }

    /**
     * Called when a view has been clicked.
     * 
     * @param v The view that was clicked.
     */
    public abstract void onSingleClick(View v);

    /**
     * Wraps an {@link OnClickListener} into an {@link OnSingleClickListener}.<br/>
     * The argument's {@link OnClickListener#onClick(View)} method will be called when a single click is registered.
     * 
     * @param onClickListener The listener to wrap.
     * @return the wrapped listener.
     */
    public static OnClickListener wrap(final OnClickListener onClickListener) {
        return new OnSingleClickListener() {
            @Override
            public void onSingleClick(View v) {
                onClickListener.onClick(v);
            }
        };
    }
}
于 2013-12-03T10:12:40.770 回答
9

你可以使用这个项目:https ://github.com/fengdai/clickguard 用一个语句来解决这个问题:

ClickGuard.guard(button);

更新:不再推荐这个库。我更喜欢 Nikita 的解决方案。请改用 RxBinding。

于 2015-02-11T03:56:29.697 回答
7

这是一个简单的例子:

public abstract class SingleClickListener implements View.OnClickListener {
    private static final long THRESHOLD_MILLIS = 1000L;
    private long lastClickMillis;

    @Override public void onClick(View v) {
        long now = SystemClock.elapsedRealtime();
        if (now - lastClickMillis > THRESHOLD_MILLIS) {
            onClicked(v);
        }
        lastClickMillis = now;
    }

    public abstract void onClicked(View v);
}
于 2014-03-13T18:59:39.197 回答
5

只是对 GreyBeardedGeek 解决方案的快速更新。更改 if 子句并添加 Math.abs 函数。像这样设置它:

  if(previousClickTimestamp == null || (Math.abs(currentTimestamp - previousClickTimestamp.longValue()) > minimumInterval)) {
        onDebouncedClick(clickedView);
    }

用户可以更改 Android 设备上的时间并将其放在过去,因此如果没有这个可能会导致错误。

PS:没有足够的积分来评论您的解决方案,所以我只是提出另一个答案。

于 2015-06-03T13:23:45.470 回答
5

所以,这个答案是由 ButterKnife 库提供的。

package butterknife.internal;

import android.view.View;

/**
 * A {@linkplain View.OnClickListener click listener} that debounces multiple clicks posted in the
 * same frame. A click on one button disables all buttons for that frame.
 */
public abstract class DebouncingOnClickListener implements View.OnClickListener {
  static boolean enabled = true;

  private static final Runnable ENABLE_AGAIN = () -> enabled = true;

  @Override public final void onClick(View v) {
    if (enabled) {
      enabled = false;
      v.post(ENABLE_AGAIN);
      doClick(v);
    }
  }

  public abstract void doClick(View v);
}

此方法仅在处理了上一次单击后才处理单击,并注意它避免了帧中的多次单击。

于 2020-05-13T08:18:35.967 回答
5

这是适用于任何事件的东西,而不仅仅是点击。即使它是一系列快速事件的一部分(如rx debounce),它也会传递最后一个事件。

class Debouncer(timeout: Long, unit: TimeUnit, fn: () -> Unit) {

    private val timeoutMillis = unit.toMillis(timeout)

    private var lastSpamMillis = 0L

    private val handler = Handler()

    private val runnable = Runnable {
        fn()
    }

    fun spam() {
        if (SystemClock.uptimeMillis() - lastSpamMillis < timeoutMillis) {
            handler.removeCallbacks(runnable)
        }
        handler.postDelayed(runnable, timeoutMillis)
        lastSpamMillis = SystemClock.uptimeMillis()
    }
}


// example
view.addOnClickListener.setOnClickListener(object: View.OnClickListener {
    val debouncer = Debouncer(1, TimeUnit.SECONDS, {
        showSomething()
    })

    override fun onClick(v: View?) {
        debouncer.spam()
    }
})

1) 在侦听器的一个字段中但在回调函数之外构造 Debouncer,配置超时和要限制的回调 fn。

2) 在监听器的回调函数中调用你的 Debouncer 的 spam 方法。

于 2017-08-30T09:07:01.557 回答
4

使用 RxJava 的类似解决方案

import android.view.View;

import java.util.concurrent.TimeUnit;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subjects.PublishSubject;

public abstract class SingleClickListener implements View.OnClickListener {
    private static final long THRESHOLD_MILLIS = 600L;
    private final PublishSubject<View> viewPublishSubject = PublishSubject.<View>create();

    public SingleClickListener() {
        viewPublishSubject.throttleFirst(THRESHOLD_MILLIS, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<View>() {
                    @Override
                    public void call(View view) {
                        onClicked(view);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        viewPublishSubject.onNext(v);
    }

    public abstract void onClicked(View v);
}
于 2016-01-08T10:51:02.563 回答
4

您可以为此目的使用 Rxbinding3。只需在 build.gradle 中添加此依赖项

build.gradle

implementation 'com.jakewharton.rxbinding3:rxbinding:3.1.0'

然后在您的活动或片段中,使用以下代码

your_button.clicks().throttleFirst(10000, TimeUnit.MILLISECONDS).subscribe {
    // your action
}
于 2020-10-12T10:19:01.447 回答
3

Signal AppHandler基于节流阀。

import android.os.Handler;
import android.support.annotation.NonNull;

/**
 * A class that will throttle the number of runnables executed to be at most once every specified
 * interval.
 *
 * Useful for performing actions in response to rapid user input where you want to take action on
 * the initial input but prevent follow-up spam.
 *
 * This is different from a Debouncer in that it will run the first runnable immediately
 * instead of waiting for input to die down.
 *
 * See http://rxmarbles.com/#throttle
 */
public final class Throttler {

    private static final int WHAT = 8675309;

    private final Handler handler;
    private final long    thresholdMs;

    /**
     * @param thresholdMs Only one runnable will be executed via {@link #publish} every
     *                  {@code thresholdMs} milliseconds.
     */
    public Throttler(long thresholdMs) {
        this.handler     = new Handler();
        this.thresholdMs = thresholdMs;
    }

    public void publish(@NonNull Runnable runnable) {
        if (handler.hasMessages(WHAT)) {
            return;
        }

        runnable.run();
        handler.sendMessageDelayed(handler.obtainMessage(WHAT), thresholdMs);
    }

    public void clear() {
        handler.removeCallbacksAndMessages(null);
    }
}

示例用法:

throttler.publish(() -> Log.d("TAG", "Example"));

中的示例用法OnClickListener

view.setOnClickListener(v -> throttler.publish(() -> Log.d("TAG", "Example")));

示例 Kt 用法:

view.setOnClickListener {
    throttler.publish {
        Log.d("TAG", "Example")
    }
}

或带有扩展名:

fun View.setThrottledOnClickListener(throttler: Throttler, function: () -> Unit) {
    throttler.publish(function)
}

然后示例用法:

view.setThrottledOnClickListener(throttler) {
    Log.d("TAG", "Example")
}
于 2019-06-02T18:46:41.347 回答
1

处理这种情况的更重要方法是在 RxJava2 中使用 Throttling 运算符(Throttle First)。在 Kotlin 中实现这一目标的步骤:

1)。依赖项:- 在 build.gradle 应用程序级别文件中添加 rxjava2 依赖项。

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.10'

2)。构造一个实现 View.OnClickListener 的抽象类,并包含油门优先运算符来处理视图的 OnClick() 方法。代码片段如下:

import android.util.Log
import android.view.View
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject
import java.util.concurrent.TimeUnit

abstract class SingleClickListener : View.OnClickListener {
   private val publishSubject: PublishSubject<View> = PublishSubject.create()
   private val THRESHOLD_MILLIS: Long = 600L

   abstract fun onClicked(v: View)

   override fun onClick(p0: View?) {
       if (p0 != null) {
           Log.d("Tag", "Clicked occurred")
           publishSubject.onNext(p0)
       }
   }

   init {
       publishSubject.throttleFirst(THRESHOLD_MILLIS, TimeUnit.MILLISECONDS)
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe { v -> onClicked(v) }
   }
}

3)。在活动中单击视图时实现此 SingleClickListener 类。这可以实现为:

override fun onCreate(savedInstanceState: Bundle?)  {
   super.onCreate(savedInstanceState)
   setContentView(R.layout.activity_main)

   val singleClickListener = object : SingleClickListener(){
      override fun onClicked(v: View) {
       // operation on click of xm_view_id
      }
  }
xm_viewl_id.setOnClickListener(singleClickListener)
}

在应用程序中实施上述这些步骤可以简单地避免多次点击视图直到 600 毫秒。快乐编码!

于 2019-10-22T10:51:39.960 回答
1

我将此类与数据绑定一起使用。效果很好。

/**
 * This class will prevent multiple clicks being dispatched.
 */
class OneClickListener(private val onClickListener: View.OnClickListener) : View.OnClickListener {
    private var lastTime: Long = 0

    override fun onClick(v: View?) {
        val current = System.currentTimeMillis()
        if ((current - lastTime) > 500) {
            onClickListener.onClick(v)
            lastTime = current
        }
    }

    companion object {
        @JvmStatic @BindingAdapter("oneClick")
        fun setOnClickListener(theze: View, f: View.OnClickListener?) {
            when (f) {
                null -> theze.setOnClickListener(null)
                else -> theze.setOnClickListener(OneClickListener(f))
            }
        }
    }
}

我的布局看起来像这样

<TextView
        app:layout_constraintTop_toBottomOf="@id/bla"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:gravity="center"
        android:textSize="18sp"
        app:oneClick="@{viewModel::myHandler}" />
于 2018-04-30T14:28:28.113 回答
0

removeall我的解决方案,当我们从片段和活动中退出(销毁)时需要调用:

import android.os.Handler
import android.os.Looper
import java.util.concurrent.TimeUnit

    //single click handler
    object ClickHandler {

        //used to post messages and runnable objects
        private val mHandler = Handler(Looper.getMainLooper())

        //default delay is 250 millis
        @Synchronized
        fun handle(runnable: Runnable, delay: Long = TimeUnit.MILLISECONDS.toMillis(250)) {
            removeAll()//remove all before placing event so that only one event will execute at a time
            mHandler.postDelayed(runnable, delay)
        }

        @Synchronized
        fun removeAll() {
            mHandler.removeCallbacksAndMessages(null)
        }
    }
于 2019-07-15T06:26:01.007 回答
0

这是一个非常简单的解决方案,可以与 lambdas 一起使用:

view.setOnClickListener(new DebounceClickListener(v -> this::doSomething));

这是复制/粘贴准备好的片段:

public class DebounceClickListener implements View.OnClickListener {

    private static final long DEBOUNCE_INTERVAL_DEFAULT = 500;
    private long debounceInterval;
    private long lastClickTime;
    private View.OnClickListener clickListener;

    public DebounceClickListener(final View.OnClickListener clickListener) {
        this(clickListener, DEBOUNCE_INTERVAL_DEFAULT);
    }

    public DebounceClickListener(final View.OnClickListener clickListener, final long debounceInterval) {
        this.clickListener = clickListener;
        this.debounceInterval = debounceInterval;
    }

    @Override
    public void onClick(final View v) {
        if ((SystemClock.elapsedRealtime() - lastClickTime) < debounceInterval) {
            return;
        }
        lastClickTime = SystemClock.elapsedRealtime();
        clickListener.onClick(v);
    }
}

享受!

于 2018-08-17T19:19:06.837 回答
0

这是这样解决的

Observable<Object> tapEventEmitter = _rxBus.toObserverable().share();
Observable<Object> debouncedEventEmitter = tapEventEmitter.debounce(1, TimeUnit.SECONDS);
Observable<List<Object>> debouncedBufferEmitter = tapEventEmitter.buffer(debouncedEventEmitter);

debouncedBufferEmitter.buffer(debouncedEventEmitter)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<List<Object>>() {
      @Override
      public void call(List<Object> taps) {
        _showTapCount(taps.size());
      }
    });
于 2016-07-05T15:31:47.323 回答
0

基于@GreyBeardedGeek 的 回答

  • 创建debounceClick_last_Timestampids.xml以标记上一次点击时间戳。
  • 将此代码块添加到BaseActivity

    protected void debounceClick(View clickedView, DebouncedClick callback){
        debounceClick(clickedView,1000,callback);
    }
    
    protected void debounceClick(View clickedView,long minimumInterval, DebouncedClick callback){
        Long previousClickTimestamp = (Long) clickedView.getTag(R.id.debounceClick_last_Timestamp);
        long currentTimestamp = SystemClock.uptimeMillis();
        clickedView.setTag(R.id.debounceClick_last_Timestamp, currentTimestamp);
        if(previousClickTimestamp == null 
              || Math.abs(currentTimestamp - previousClickTimestamp) > minimumInterval) {
            callback.onClick(clickedView);
        }
    }
    
    public interface DebouncedClick{
        void onClick(View view);
    }
    
  • 用法:

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            debounceClick(v, 3000, new DebouncedClick() {
                @Override
                public void onClick(View view) {
                    doStuff(view); // Put your's click logic on doStuff function
                }
            });
        }
    });
    
  • 使用 lambda

    view.setOnClickListener(v -> debounceClick(v, 3000, this::doStuff));
    
于 2018-10-25T21:21:09.833 回答
0

在这里放一个小例子

view.safeClick { doSomething() }

@SuppressLint("CheckResult")
fun View.safeClick(invoke: () -> Unit) {
    RxView
        .clicks(this)
        .throttleFirst(300, TimeUnit.MILLISECONDS)
        .subscribe { invoke() }
}
于 2019-01-16T18:49:59.623 回答
0

我想说最简单的方法是使用像 KProgressHUD 这样的“加载”库。

https://github.com/Kaopiz/KProgressHUD

onClick 方法的第一件事是调用加载动画,它会立即阻止所有 UI,直到开发人员决定释放它。

所以你会在 onClick 动作中使用它(这使用 Butterknife,但它显然适用于任何类型的方法):

另外,不要忘记在单击后禁用按钮。

@OnClick(R.id.button)
void didClickOnButton() {
    startHUDSpinner();
    button.setEnabled(false);
    doAction();
}

然后:

public void startHUDSpinner() {
    stopHUDSpinner();
    currentHUDSpinner = KProgressHUD.create(this)
            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setLabel(getString(R.string.loading_message_text))
            .setCancellable(false)
            .setAnimationSpeed(3)
            .setDimAmount(0.5f)
            .show();
}

public void stopHUDSpinner() {
    if (currentHUDSpinner != null && currentHUDSpinner.isShowing()) {
        currentHUDSpinner.dismiss();
    }
    currentHUDSpinner = null;
}

如果您愿意,可以在 doAction() 方法中使用 stopHUDSpinner 方法:

private void doAction(){ 
   // some action
   stopHUDSpinner()
}

根据您的应用逻辑重新启用按钮: button.setEnabled(true);

于 2019-09-12T17:42:48.703 回答