我想创建一个每 50 毫秒运行一次的函数(相当于 JS 中的setInterval
(。到目前为止,这就是我所拥有的:
val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post(object: Runnable {
override fun run() {
progressBar.progress += 1
mainHandler.postDelayed(this, 50)
}
})
它可以工作,但是当进度达到100
时,如何阻止run()
函数进一步运行?另外,有没有办法取消run
并在单击按钮(如 JS 中的clearInterval
(时将progress
重置为0
?作为参考,我想要这个:
buttonView.setOnClickListener {
stopRunFromRunning()
resetProgressTo0()
}
progress.onReach100 {
stopRunFromRunning()
}
将可运行对象分配给变量,您可以从处理程序的回调中删除
val progressBar = findViewById(R.id.progress_bar)
val btn = findViewById(R.id.btn)
val handler = Handler(Looper.getMainLooper())
val runnable = Runnable {
override public fun run() {
progressBar.progress+=1
if(progressBar.progress<100)
handler.postDelayed(this, 50)
}
}
handler.post(runnable, milliseconds)
btn.setOnClickListener {
handler.removeCallbacks(runnable)
progressBar.progress=0
}
使用进度条时,我会执行以下操作:
var stop = false
val runnable = Runnable {
while (progressBar.progress < 100) {
if(stop) break
progressBar.progress += 1
// Try to sleep the thread for 50 milliseconds
try {
Thread.sleep(50)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
Thread(runnable).start()
// stop
stopButtonClick -> {
stop = true
progressBar.progress = 0
}
现在,您可以告诉您的计数器在progressBar.progress = 100
之前停止,并且您的计数器也知道何时停止。希望对你有帮助