我有一个可组合的,它得到一个整数,它是一个可变状态!
整数 是一个计时器值!像 0 每秒增加
我必须在可组合中做的是转换为可表示的字符串,例如 60 秒我将显示 1 分钟
所以我这样做
val timeString = remember {
mutableStateOf("00:00")
}
val durationString = if(duration!=0) {
var secondTime = ((duration / 1000) % 60).toString()
var minuteTime = ((((duration / 1000) / 60) % 60)).toString()
if (secondTime.length == 1) {
secondTime = "0$secondTime"
}
if (minuteTime.length == 1) {
minuteTime = "0$minuteTime"
}
"$minuteTime:$secondTime"
}else{
"00:00"
}
timeString.value = durationString
Text(
modifier = Modifier
.weight(1f)
.padding(horizontal = 16.dp),
text = timeString.value,
style = MaterialTheme.typography.h4
)
但文本不会更新,但由于持续时间是可变状态,如果我直接使用它,文本会更新,所以我尝试了 LaunchedEffect 但它没有用我想知道我能做到的最好方法是什么撰写!
答案 0 :(得分:1)
就像在我的评论中提到的那样,您需要扭曲每次应该在记忆中重新计算的内容并将状态作为键传递(需要这样 compose 知道它必须更新字符串)。
查看示例代码:
@Composable
fun outer() {
val durationState = remember { mutableStateOf(600000) }
LaunchedEffect(durationState) {
// This not how you do a timer but close enough
val step = 1000
repeat(600000.div(step)) {
durationState.value = durationState.value - step
delay(step.toLong())
}
}
questionComposable(durationState)
}
@Composable
fun questionComposable(durationState: MutableState<Int>) {
val durationString = remember(durationState.value) {
val duration = durationState.value
if (duration != 0) {
var secondTime = ((duration / 1000) % 60).toString()
var minuteTime = ((((duration / 1000) / 60) % 60)).toString()
if (secondTime.length == 1) {
secondTime = "0$secondTime"
}
if (minuteTime.length == 1) {
minuteTime = "0$minuteTime"
}
"$minuteTime:$secondTime"
} else {
"00:00"
}
}
Text(
text = durationString,
style = MaterialTheme.typography.h4
)
}