我想实现与Android设置应用程序的开发人员选项类似的行为。我的意思是,当用户按下一个按钮7次并且每次点击之间有短暂延迟时,将弹出一个窗口询问他是否要在应用程序中启用一个隐藏功能。
我该如何实现这种行为?
我该如何实现这种行为?
TimerWatchDog
的实例会执行该任务。ContinuousClicksHandler
使用TimerWatchDog
的一个实例以及计数点击次数。
val clicksCount = 7
val maxInterval = 1000L
val continuousClicksHandler = ContinuousClicksHandler(clicksCount, maxInterval)
continuousClicksHandler.registerCallback(object : ContinuousClicksHandler.ContinuousClicksCallback {
override fun onContinuousClicksSuccessful() {
println("onContinuousClicksSuccessful!")
}
override fun onContinuousClicksFailed() {
println("onContinuousClicksFailed!")
}
})
button.setOnClickListener {
val count = continuousClicksHandler.click()
showToast("Needs ${clicksCount - count} more clicks to succeed!")
}
ContinuousClicksHandler.kt
/**
* @author aminography
*/
class ContinuousClicksHandler(
private val clicksCount: Int,
maxInterval: Long
) {
private var callback: ContinuousClicksCallback? = null
private val timerWatchDog = TimerWatchDog(maxInterval)
private var currentClicks = 0
fun click(): Int {
if (++currentClicks == clicksCount) {
timerWatchDog.cancel()
currentClicks = 0
callback?.onContinuousClicksSuccessful()
} else {
timerWatchDog.refresh {
currentClicks = 0
callback?.onContinuousClicksFailed()
}
}
return currentClicks
}
fun registerCallback(callback: ContinuousClicksCallback) {
this.callback = callback
}
interface ContinuousClicksCallback {
fun onContinuousClicksSuccessful()
fun onContinuousClicksFailed()
}
}
TimerWatchDog.kt
import java.util.*
/**
* @author aminography
*/
class TimerWatchDog(private val timeout: Long) {
private var timer: Timer? = null
fun refresh(job: () -> Unit) {
timer?.cancel()
timer = Timer()
timer?.schedule(object : TimerTask() {
override fun run() = job.invoke()
}, timeout)
}
fun cancel() = timer?.cancel()
}
...
view.setOnClickListener(continuousClickListener);
...
private final View.OnClickListener continuousClickListener = new View.OnClickListener() {
private long lastTimeMs = 0;
private int clickCount = 0;
@Override
public void onClick(View v) {
long now = System.currentTimeMillis();
if (lastTimeMs == 0 || now - lastTimeMs < 500) {
lastTimeMs = now;
clickCount++;
if (clickCount >= 7) {
// do stuff
showToast("quiz enabled");
} else {
if (clickCount > 2) {
showToast((7-clickCount) + " more for quiz");
}
}
} else {
lastTimeMs = 0;
clickCount = 0;
}
}
};