Praneeth Bhargav
Praneeth Bhargav

Reputation: 73

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

Upvotes: 2

Views: 1832

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363737

Check how compose works with states and recomposition.

Use something like:

var i by remember { mutableStateOf(0) }

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

Upvotes: 3

Related Questions