Home > Enterprise >  Text is not updating on button in Jetpack Compose
Text is not updating on button in Jetpack Compose

Time:06-24

I want to change the text that's appearing on the button each time I click it, so I have written the following code, but it's not working. Where am I going wrong?

    class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            var i=0;
            Button(onClick = {i   }) {
                Text("Clicked $i times") //!!not updating here
            }
        }
    }
}

CodePudding user response:

Check how compose works with states and recomposition.

Use something like:

var i by remember { mutableStateOf(0) }

Button(onClick = {i   }) {
    Text("Clicked $i times")
}
  • Related