I'm new to jetpack compose and I have created a composable function with a simple text.
I would like to update it every time a timer reaches timer.ontick
function
but it does not work. Any help?
fun LKIDView(text : String, onLKIDViewChange: (String) -> Unit) {
var lkidState by remember { mutableStateOf("Default") }
val onlkidChange={text : String -> lkidState = text}
Column(
horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier
.fillMaxWidth()
.background(Color(0xFF7DCEA0))
) {
Text(
text = lkidState,
// modifier = Modifier.fillMaxWidth(),
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.SansSerif,
//
)
}
}`
`
My ontimer.tick looks like this
`val timer = object : CountDownTimer(Gtime, Ttime) {
var lkidviewState = remember { mutableStateOf("Landkreis/Kreeisfreie Stadt") }
val onTextChange={text : String -> lkidviewState.value = text}
override fun onTick(millisUntilFinished: Long) {
Log.e("TimerTick - ", "Tick ")
LKIDView(text =lkidviewState.value , onLKIDViewChange = onTextChange)
// lkidviewState.value = "dsfdsfdsf"`}`
Android Studio says composable invocation can only happen from the context of a composable function
timer runs - the code did not update the ui
CodePudding user response:
Compose doesn't work in this way.
You can't call a composable inside the CountDownTimer
to display the updated value.
Instead you have to use a state (lkidState
), and then CountDownTimer
has to update this value.
val lkidState = remember {
mutableStateOf(0)
}
val timer = object : CountDownTimer(0, 1000) {
override fun onTick(millisUntilFinished: Long) {
lkidState.value = millisUntilFinished
}
//...
}
Text(text = lkidState.value.toString())
Final note, I would use other option instead of a CountDownTimer, like a side effect.