我想实现与开发人员选项的 android 设置应用程序类似的行为。我的意思是当用户连续点击按钮 7 次并且每次点击之间有一个小的延迟时,会出现一个弹出窗口,要求他启用应用程序中的隐藏功能。
我该如何实现这种行为?
I have developed it based on the watchdog concept. An instance of TimerWatchDog does the job if it doesn't refresh in the specified time. ContinuousClicksHandler uses an instance of TimerWatchDog along with counting the clicks.
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!")
}
Run Code Online (Sandbox Code Playgroud)
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()
}
}
Run Code Online (Sandbox Code Playgroud)
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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
763 次 |
| 最近记录: |