androidkotlinandroid-jetpack-composeandroid-jetpackandroid-compose-button

Text is not updating on button in Jetpack Compose


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
            }
        }
    }
}

Solution

  • Check how compose works with states and recomposition.

    Use something like:

    var i by remember { mutableStateOf(0) }
    
    Button(onClick = {i++ }) {
        Text("Clicked $i times")
    }