SNM
SNM

Reputation: 6835

How to mark a button as selectable with jetpack compose

I want to mark a button as selected or unselected, if its unselected it should show a gray background (not selected) and if its selected I would like to show it color, I want to prevent an else branch like this

val voteState = remember { mutableStateOf(false)}

     if(voteState.value){
                Button(onClick = {
                    onVotePollClick(poll)
                }, modifier = Modifier.width(200.dp).align(Alignment.CenterHorizontally).clip(
                        CircleShape
                )) {
                    Text(text = "Vote")
                }
            }else{
                Button(onClick = {
                    onVotePollClick(poll)
                }, modifier = Modifier.width(200.dp).align(Alignment.CenterHorizontally).clip(
                        CircleShape
                ).background(Color.Gray)) {
                    Text(text = "Vote")
                }
            }

And I want the button to react to the voteState value, if false it should not be clickable and only show a grey unselected background, if its set to true I would like to show the button at it is

Currently, the Button composable does not have a selected parameter so I find this a little of boilerplate to implement this feature somehow

Upvotes: 3

Views: 2732

Answers (1)

SNM
SNM

Reputation: 6835

Solved it by just using the enabled parameter

  Button(onClick = {
                    onVotePollClick(poll)
                }, modifier = Modifier.width(200.dp).align(Alignment.CenterHorizontally).clip(
                        CircleShape
                ),enabled = voteState.value) {
                    Text(text = "Vote")
                }

Upvotes: 3

Related Questions