Avoid button multiple rapid clicks

前端 未结 20 1474
猫巷女王i
猫巷女王i 2020-11-28 02:55

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 disappear

20条回答
  •  爱一瞬间的悲伤
    2020-11-28 03:16

    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 minimumIntervalMillis;
        private Map 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);
            }
        }
    }
    

提交回复
热议问题