I am new to both Kotlin and Android Studio. Using some online guides I have been able to create some very simple UIs. I now have a problem that one of my UIs will not recompose when I use a property of a class within a composable. Below is my code. I create a class that has an INT property which is initialized to 3 and a method that will increase the property’s value. I am using the property value in the text of a button.
class Cards {
var number: Int = 3
fun incNum() {
number++
}
}
@Composable
fun TestApp() {
val myCard by remember { mutableStateOf(Cards()) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Button(onClick = {
myCard.incNum()
}) {
Text(
text = "Clicks: ${myCard.number.toString()}",
fontSize = 50.sp
)
}
}
}
When I click the button the value of the property increases but the new value does not display in the text of the button. I have used the debugger and verified that the new value of the property is maintained between clicks (3, 4, 5, etc.) but no recomposition occurs.
I don’t understand why the UI will not update. Any help with this will be greatly appreciated. Let me know if you need more information about the problem.
thanks,
tom.
user26562650 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.