android防止按钮多次点击和添加双击事件

如下:自定义一个抽象类实现View.OnClickListener接口,在onclick方法中判断点击的时间间隔,根据时间间隔调用相应的抽象方法即可在调用处得到回调,可根据需求定义不同的接口和抽象类(单击,双击,单击+双击)

“`java
public abstract class MyClickListener implements View.OnClickListener {

private final int MIN_CLICK_DELAY_TIME = 1000;
private final int DOUBLE_CLICK_DELAY_TIME = 200;
private long lastClickTime = 0;
private final int SINGLE_CLICK_MESSAGE = 1;
//调用单击方法的handler
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        myOnSingleClick((View) msg.obj);
    }
};

@Override
public void onClick(final View v) {
    long currentTime = System.currentTimeMillis();
    if (currentTime - lastClickTime < DOUBLE_CLICK_DELAY_TIME) {
        lastClickTime = currentTime;
        myOnDoubleClick(v);
        //单双击事件同时存在时,如果判断为双击则不再执行单击事件的逻辑
        handler.removeMessages(SINGLE_CLICK_MESSAGE);
        return;
    }
    if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
        lastClickTime = currentTime;
        Message msg = new Message();
        msg.obj = v;
        msg.what = SINGLE_CLICK_MESSAGE;
        //延迟执行单击事件,避免先执行了单击事件由执行双击事件
        handler.sendMessageDelayed(msg, DOUBLE_CLICK_DELAY_TIME + 1);
    }

}

public abstract void myOnSingleClick(View v);

public abstract void myOnDoubleClick(View v);
}       

“`

你可能感兴趣的:(android防止按钮多次点击和添加双击事件)