Last active
March 20, 2018 05:09
-
-
Save li2/085b96168b6c8563c2f4 to your computer and use it in GitHub Desktop.
Android 连续多次点击事件回调接口。Interface definition for a callback to be invoked when a view is multiple clicked. 继承自 View.OnClickListener,当连续多次点击时被回调。点击之间的间隔必须小于给定值,才能被识别为一次连续的点击;当点击之间的间隔超时后,丢弃之前记录的点击,重新开始记录。 #tags: android-view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.SystemClock; | |
import android.view.View; | |
import java.util.Map; | |
import java.util.WeakHashMap; | |
// 源码基于 http://stackoverflow.com/questions/16534369/avoid-button-multiple-rapid-clicks | |
public abstract class OnMultipleClickListener implements View.OnClickListener { | |
private static final int DEFAULT_MAX_INTERVAL = 1000; // ms | |
private int mClickIndex; | |
private int mContinuousClickCount; | |
private final long mMaxInterval; | |
private Map<View, Long> mClickMap; | |
/** | |
* Implement this in your subclass instead of onClick | |
* @param v The view that was clicked | |
*/ | |
public abstract void onMultipleClick(View v); | |
public OnMultipleClickListener(int multiple) { | |
this(multiple, DEFAULT_MAX_INTERVAL); | |
} | |
/** | |
* Constructor | |
* @param maxIntervalMsec The max allowed time between clicks, or else discard all previous clicks. | |
*/ | |
public OnMultipleClickListener(int multiple, long maxIntervalMsec) { | |
mClickIndex = 0; | |
mContinuousClickCount = multiple; | |
mMaxInterval = maxIntervalMsec; | |
mClickMap = new WeakHashMap<View, Long>(); | |
} | |
@Override public void onClick(View clickedView) { | |
Long previousClickTimestamp = mClickMap.get(clickedView); | |
long currentTimestamp = SystemClock.uptimeMillis(); | |
mClickMap.put(clickedView, currentTimestamp); | |
if (previousClickTimestamp == null) { | |
// first click | |
mClickIndex = 1; | |
} else { | |
// other click | |
if ((currentTimestamp - previousClickTimestamp.longValue()) < mMaxInterval) { | |
++mClickIndex; | |
if (mClickIndex >= mContinuousClickCount) { | |
mClickIndex = 0; | |
mClickMap.clear(); | |
onMultipleClick(clickedView); | |
} | |
} else { | |
// timeout | |
mClickIndex = 1; | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 3 click, 1000 ms | |
// 连续 3 次点击,并且点击之间的间隔不能超过 1000ms,才能被回调。 | |
view.setOnClickListener(new OnMultipleClickListener(3, 1000) { | |
@Override | |
public void onMultipleClick(View v) { | |
// do some stuff when multiple clicked. | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment