一.需求描述
在Andorid的实际开发中经常会用到倒计时,无论是可见的进度条,倒计时,广告,还是背后的一些操作,今天来总结下几种倒计时的实现方法。
二.实现方式
1.使用 CountDownTimer
类:
val countDownTimer = object : CountDownTimer(30000, 1000) {
override fun onTick(millisUntilFinished: Long) {
// 在倒计时的过程中,每秒钟会执行一次该方法
val secondsRemaining = millisUntilFinished / 1000
// 更新UI,显示剩余秒数
textView.text = "倒计时:$secondsRemaining 秒"
}
override fun onFinish() {
// 倒计时结束时会执行该方法
textView.text = "倒计时结束"
}
}
// 开始倒计时
countDownTimer.start()
如果达到某个条件需要取消倒计时:countDownTimer.start()
2. 使用 Handler
和 Runnable
:
private var countDownValue = 30
private lateinit var countDownHandler: Handler
private lateinit var countDownRunnable: Runnable
private fun startCountDown() {
countDownHandler = Handler()
countDownRunnable = object : Runnable {
override fun run() {
if (countDownValue > 0) {
// 更新UI,显示剩余秒数
textView.text = "倒计时:$countDownValue 秒"
countDownValue--
countDownHandler.postDelayed(this, 1000)
} else {
// 倒计时结束时执行的操作
textView.text = "倒计时结束"
}
}
}
// 开始倒计时
countDownHandler.post(countDownRunnable)
}
// 在需要启动倒计时的地方调用 startCountDown() 方法
当然你也可以使用这俩货实现定时任务
需求是在某一段时间内,不断的切换图片的资源,因为UI没时间做动画,所以自己简单实现一下
private lateinit var handler: Handler private lateinit var runnable: Runnable private var currentImageIndex = 0 private val imageList = listOf(R.mipmap.second_bg_2, R.mipmap.second_bg_ok) // 替换成你的图片资源 //在合适的地方初始化 handler = Handler() runnable = Runnable { switchImage() }
private fun startImageSwitching() {
handler.postDelayed(runnable, 1000) // 1 秒后开始切换图片
}
private fun switchImage() {
currentImageIndex = (currentImageIndex + 1) % imageList.size // 循环切换图片
mBinding.secondBg2.setImageResource(imageList[currentImageIndex])
handler.postDelayed(runnable, 500) // 0.5 秒后继续切换图片
}
private fun stopImageSwitching() {
handler.removeCallbacks(runnable)
if (NormalVariable.coreServiceState == BaseService.State.Connected) {
mBinding.secondBg2.setImageResource(imageList[1])
} else {
mBinding.secondBg2.setImageResource(imageList[0])
}
}
3.使用 Coroutines:
private var countDownValue = 30
private var countDownJob: Job? = null
private fun startCountDown() {
countDownJob = CoroutineScope(Dispatchers.Main).launch {
while (countDownValue > 0) {
// 更新UI,显示剩余秒数
textView.text = "倒计时:$countDownValue 秒"
delay(1000) // 暂停1秒钟
countDownValue--
}
// 倒计时结束时执行的操作
textView.text = "倒计时结束"
}
}
// 在需要启动倒计时的地方调用 startCountDown() 方法
4.使用 Timer 类:
private var countDownValue = 30
private var countDownTimer: Timer? = null
private fun startCountDown() {
countDownTimer = Timer()
countDownTimer?.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
if (countDownValue > 0) {
// 更新UI,显示剩余秒数
textView.text = "倒计时:$countDownValue 秒"
countDownValue--
} else {
// 倒计时结束时执行的操作
textView.text = "倒计时结束"
countDownTimer?.cancel()
}
}
}, 0, 1000) // 每隔1秒执行一次
}
// 在需要启动倒计时的地方调用 startCountDown() 方法
以上就是android中,我常常用来实现倒计时的四种方式。看哪个合适你就用哪个哈