0%

Android小技巧OnClickListener去重

当View被快速多次点击,onClickListener事件的onClick(View view)会执行多次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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 {
private static final Runnable ENABLE_AGAIN = () -> enabled = true;
private static final Handler MAIN = new Handler(Looper.getMainLooper());

static boolean enabled = true;

@Override public final void onClick(View v) {
if (enabled) {
enabled = false;

// Post to the main looper directly rather than going through the view.
// Ensure that ENABLE_AGAIN will be executed, avoid static field {@link #enabled}
// staying in false state.
MAIN.post(ENABLE_AGAIN);

doClick(v);
}
}

public abstract void doClick(View v);
}

来源:butterknife中DebouncingOnClickListener

赞赏是最好的支持