避免按钮多次快速点击按钮、快速

2023-09-05 06:03:02 作者:帅飞一条街

我有我的应用程序的一个问题是,如果用户点击按钮多次快,连我对话之前产生那么多的事件按住按钮消失

I have a problem with my app that if the user clicks the button multiple times quickly, then multiple events are generated before even my dialog holding the button disappears

我知道,通过设置一个布尔变量作为标志,当点击一个按钮,以便未来的点击可以pvented,直到对话框关闭$ P $的解决方案。不过,我有很多按钮,不得不这样做,每次为每个按钮似乎是矫枉过正。是否有安卓没有其他办法(或者一些更聪明的解决方案),以允许每个按键只产生唯一的事件操作单击?

I know a solution by setting a boolean variable as a flag when a button is clicked so future clicks can be prevented until the dialog is closed. However I have many buttons and having to do this everytime for every buttons seems to be an overkill. Is there no other way in android (or maybe some smarter solution) to allow only only event action generated per button click?

什么是更糟糕的是,多简单的点击,似乎产生多个事件行动之前,连第一个动作的处理,所以如果我想禁用的第一次单击操作方法的按钮,在队列中有已经存在的事件操作等待办理!

What's even worse is that multiple quick clicks seems to generate multiple event action before even the first action is handled so if I want to disable the button in the first click handling method, there are already existing events actions in the queue waiting to be handled!

请帮忙 谢谢

推荐答案

下面是一个反跳的onClick监听器,我最近写了。 你告诉它什么毫秒点击之间可接受的最小数量为。 实现而不是的onClick你的逻辑在 onDebouncedClick

Here's a 'debounced' onClick listener that I wrote recently. You tell it what the minimum acceptable number of milliseconds between clicks is. Implement your logic in onDebouncedClick instead of 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 minimumInterval;
    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 minimumIntervalMsec The minimum allowed time between clicks - any click sooner than this after a previous click will be rejected
     */
    public DebouncedOnClickListener(long minimumIntervalMsec) {
        this.minimumInterval = minimumIntervalMsec;
        this.lastClickMap = new WeakHashMap<View, Long>();
    }

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

        lastClickMap.put(clickedView, currentTimestamp);
        if(previousClickTimestamp == null || (currentTimestamp - previousClickTimestamp.longValue() > minimumInterval)) {
            onDebouncedClick(clickedView);
        }
    }
}