自定义一个NoDoubleClickListener类,实现OnClickListener接口:
public abstract class NoDoubleClickListener implements View.OnClickListener{privatestaticlonglastClickTime =0;publicstaticfinalintMIN_CLICK_DELAY_TIME =700;publicabstractvoidonNoDoubleClick(View view);@OverridepublicvoidonClick(View v) {longcurrentTime = Calendar.getInstance().getTimeInMillis();if(currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { lastClickTime = currentTime; onNoDoubleClick(v); } }}
使用NoDoubleClickListener代替OnClickListener来实现点击事件:
mbutton.setOnClickListener(newNoDoubleClickListener() {@OverrideprotectedvoidonNoDoubleClick(View v) { doSomeThing(); } });}
1. 在View的setOnClickListener中可以看到OnClickListener的对象赋值给了getListenerInfo().mOnClickListener
publicvoidsetOnClickListener(@Nullable OnClickListener l) {if(!isClickable()) { setClickable(true); } getListenerInfo().mOnClickListener = l;}
2. 在View类的performClick()中会调用mOnClickListener.onClick()方法
publicbooleanperformClick() {finalbooleanresult;finalListenerInfo li = mListenerInfo;if(li !=null&& li.mOnClickListener !=null) { playSoundEffect(SoundEffectConstants.CLICK); li.mOnClickListener.onClick(this); result =true; }else{ result =false; } sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);returnresult;}
3. 调用View的onClick()后,就会回调NoDoubleClickListener中的onClick()方法,经过按键防抖处理后再回调onNoDoubleClick()方法
网友评论