TextButton's text Not updating

44 views Asked by At

I am making my first app for android in jetpack compose. I am trying to make a text button that will update it's text each time it is pressed, however while it is showing just fine on the device it does not update the Button

@Composable
fun ShotButton(){
    var state by remember { mutableStateOf("N") }
    TextButton(modifier = Modifier.size(60.dp, height = 70.dp),onClick = {
        if(state == "N") state = "Y"
        if(state == "Y") state = "R"
        if(state == "R") state = "N"

    }) {
        Text(text = state, fontSize = 60.sp)
    }
}

I have done many changes to how i declare the button and the state variable, and the documentation doesn't really clear my doubts

3

There are 3 answers

0
Philio On

You could use when:

@Composable
fun ShotButton() {
    var state by remember { mutableStateOf("N") }
    TextButton(modifier = Modifier.size(60.dp, height = 70.dp), onClick = {
        when (state) {
            "N" -> state = "Y"
            "Y" -> state = "R"
            "R" -> state = "N"
        }
    }) {
        Text(text = state, fontSize = 60.sp)
    }
}
0
Nirali Pandya On

Try to use when to check different state condition like this:

onClick = {
    when(state) {
        "N" -> state = "Y"
        "Y" -> state = "R"
        "R" -> state = "N"
    }
}
0
Yves Kalume On

It's because all your if conditions are getting executed.

You can use else-if :

@Preview(showBackground = true)
@Composable
fun ShotButton(){
    var state by remember { mutableStateOf("N") }
    TextButton(modifier = Modifier.size(60.dp, height = 70.dp),onClick = {
        if(state == "N") {
            state = "Y"
        } else if(state == "Y") {
            state = "R"
        } else if(state == "R") {
            state = "N"
        }

    }) {
        Text(text = state, fontSize = 60.sp)
    }
}

or replace them by a when