Android开发封装防抖xxx秒操作
Android开发封装防抖xxx秒操作
防抖不是简单的延迟操作。是某一时间内只响应一次。
直接上工具类代码:
public class DebounceUtil {private static final Handler handler = new Handler(Looper.getMainLooper());private static final Map<String, Runnable> debounceMap = new HashMap<>();private static final int DEBOUNCE_DELAY = 500; // 500ms,可自定义public static void runDebounced(String tag, Runnable action) {Runnable old = debounceMap.get(tag);if (old != null) {handler.removeCallbacks(old);}Runnable runnable = new Runnable() {@Overridepublic void run() {action.run();debounceMap.remove(tag);}};debounceMap.put(tag, runnable);handler.postDelayed(runnable, DEBOUNCE_DELAY);}
}
使用示例:
DebounceUtil.runDebounced("mykey", () -> {new CommonPresenter<>().getChatMessagePageNum();});