需求是一段时间内连续点击3次后响应操作。
平常一般是单击,双击。
三次会用记录时间点方法来实现,还要区分>=3次 ,<3次。
而系统FirmwareVersionDetailPreferenceController源码中有一个写法:
private final long[] mHits = new long[ACTIVITY_TRIGGER_COUNT];
arrayCopy();
mHits[mHits.length - 1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis() - DELAY_TIMER_MILLIS)) {
//执行你想做的事情
}
void arrayCopy() {
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
}
这个写法的好处是,不用自己处理当前第几次。数组的长度已经限制了只会记录最近的三次。逻辑上会比较简单。但mHits[0] >= (SystemClock.uptimeMillis() 这个判断,会有几毫秒的时间戳误差.
修改后为:
class PlannerDebugMenuTouchListener(private val action:() -> Unit) : View.OnTouchListener {
private val counts = 3
private val duration: Long = 2000
private var mHits = LongArray(counts)
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
if (event != null && (event.action == MotionEvent.ACTION_UP)) {
//Go to debugMenu after 3 time click on DURATION time.
System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
mHits[mHits.size - 1] = SystemClock.uptimeMillis()
if (mHits[0] >= mHits[mHits.size - 1] - duration) {
mHits = LongArray(counts)
action()
}
}
return false
}
}