Make a button Unclickable from onClick

217 Views Asked by At

I am trying to use Compose and Kotlin in this code to make the button unclickable when counter == 3.
When I run the code and counter presumably is 3, the button stays clickable and wont change to uncklickable.

var counter = 0
var isClickable by remember { mutableStateOf(true) }

fun QuizScreen (modifier: androidx.compose.ui.Modifier) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
  ){
        Button( enabled = isClickable,onClick = {
            if(counter == 3){
                isClickable = false
            }
             
         }
   }

} 

Tried using remember variable so when I change the variable from onClick, it changes the state of the button, but it still wont change

2

There are 2 best solutions below

1
On

You can use a condition (count <3) for the enabled parameter:

    var count by rememberSaveable { mutableStateOf(0) }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
    ) {
        Text(text = "$count")
        Button(
            enabled = count <3,
            onClick = { count++ }
        ) {
            Text(text = "Count++")
        }
    }

In your code counter is not incremented and it is not a state and the Button is never recomposed.

0
On
@Composable
fun QuizScreen(modifier: Modifier = Modifier) {

   
    var count by rememberSaveable { mutableStateOf(0) }
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
    ) {
        Text(text = count.toString())
        Button( enabled = count <3,
        onClick = { count++ }
        ) {
            Text(text = "Count++")
        }
    }
}