防止按钮短时间内重复点击

时间:2022-04-28 17:13:27

类的主内容:

public class EnableDelayUtil {
private static Handler handler = new Handler();
private static ArrayList<Runnable> myRunnableList = new ArrayList<>();
private static ArrayList<View> viewList = new ArrayList<>();


public static void setDelayed(final View v) {
// handler=new Handler();
final Runnable myRunnable = new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
v.setEnabled(true);
viewList.remove(v);
myRunnableList.remove(this);
}
};
myRunnableList.add(myRunnable);
viewList.add(v);

v.setEnabled(false);

handler.postDelayed(myRunnable, 2000);
}

public static void remove() {
if (!myRunnableList.isEmpty()) {
for (Runnable myRunnable : myRunnableList) {
if (myRunnable != null) {
handler.removeCallbacks(myRunnable);
}
}
myRunnableList.clear();
}
}
}


使用方法:

在需要防止重复点击的地方调用

EnableDelayUtil.setDelayed(view) ,

然后在所处activity的结束处调用EnableDelayUtil.remove()即可。