android Jetpack合成中的CountDownTimer

5sxhfpxr  于 2023-05-12  发布在  Android
关注(0)|答案(4)|浏览(152)

我正在用下面的代码在jetpack compose中试验CountDownTimer

@Composable
fun Timer() {
    val millisInFuture: Long = 10 * 1000 // TODO: get actual value

    val timeData = remember {
        mutableStateOf(millisInFuture)
    }

    val countDownTimer =
        object : CountDownTimer(millisInFuture, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                Log.d("TAG", "onTick: ")
                timeData.value = millisInFuture
            }

            override fun onFinish() {
               
            }
        }
    
    DisposableEffect(key1 = "key") {
        countDownTimer.start()
        onDispose {
            countDownTimer.cancel()
        }
    }

    Text(
        text = timeData.value.toString()
    )
}

在logcat中,我可以看到计时器在滴答作响,但UI没有更新。请解释为什么在改变状态变量的值时没有重组。

3yhwsihp

3yhwsihp1#

你可以尝试用下面的代码来实现一个倒计时计时器:

val time = (timerDate.time).minus(Calendar.getInstance().timeInMillis)
var timer by remember { mutableStateOf(time) }
  LaunchedEffect(key1 = timer) {
      if (timer > 0) {
          delay(1000L)
          timer -= 1000L
       }
     }
  val secMilSec: Long = 1000
  val minMilSec = 60 * secMilSec
  val hourMilSec = 60 * minMilSec
  val dayMilSec = 24 * hourMilSec
  val hours = (time % dayMilSec / hourMilSec).toInt()
  val minutes = (time % dayMilSec % hourMilSec / minMilSec).toInt()
  val seconds = (time % dayMilSec % hourMilSec % minMilSec / secMilSec).toInt()

Text(text = String.format("%02d:%02d:%02d", hours, minutes, seconds))
qvk1mo1f

qvk1mo1f2#

在CountDownTimer中,您应该设置millisUntilFinished,而不是设置millisInFuture。该变量保存更新后的值,millisInFuture永远不会更改

timeData.value = millisUntilFinished
bttbmeg0

bttbmeg03#

Composable仅在状态发生变化时才重新组合,无论是来自Composable函数参数还是由Composable本身内部的State<T>的值变化(如mutableStateOf()mutableStateListOf())。在本例中,您还没有启动countDownTimer本身。尝试在DisposableEffect内部调用countDownTimer.start()。第二,您使用错误的值设置timeData,尝试使用millisUntilFinished设置它

kqhtkvqz

kqhtkvqz4#

简单的CountDownTimer只是秒

var timer by remember { mutableStateOf(durationSeconds) }
LaunchedEffect(key1 = timer) {
    if (timer > 0) {
        delay(1_000)
        timer -= 1
    }
}

Text(
    text = timer.toString()
)

相关问题