Reputation: 157
I want to disable ExposedDropdownMenuBox
based on a boolean variable
My code look something like this:
@Composable
private fun Title(
title: String,
onTitleChange: (String) -> Unit,
isTitleEnabled: Boolean
) {
val options = stringArrayResource(id = R.array.name_titles)
var expanded by remember { mutableStateOf(false) }
var selectedOptionText by remember { mutableStateOf(title) }
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
TextField(
enabled = isTitleEnabled,
modifier = Modifier
.fillMaxWidth()
.greyBordered(),
readOnly = true,
value = selectedOptionText,
onValueChange = { },
label = { Text(stringResource(id = R.string.input_hint_title)) },
trailingIcon = { TrailingIcon(expanded = expanded) },
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(
textColor = navyBlue,
focusedLabelColor = nightGray,
backgroundColor = white,
cursorColor = navyBlue,
trailingIconColor = nightGray,
focusedTrailingIconColor = nightGray,
focusedBorderColor = Color.Transparent,
unfocusedBorderColor = Color.Transparent,
disabledBorderColor = Color.Transparent,
)
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
options.forEach { selectionOption ->
DropdownMenuItem(
onClick = {
selectedOptionText = selectionOption
onTitleChange(selectionOption)
expanded = false
}
) {
Text(text = selectionOption)
}
}
}
}
}
So I have a compose function that contains ExposedDropdownMenuBox which contains textField and ExposedDropdownMenu, what I want to achieve is to be able to enable ExposedDropdownMenuBox whenever isTitleEnabled
variable is true and not be able to expand the ExposedDropdownMenuBox whenever the isTitleEnabled
variable is false.
Upvotes: 6
Views: 2199
Reputation: 5122
[...]
val options = stringArrayResource(id = R.array.name_titles)
var expanded by remember { mutableStateOf(false) }
if (DISABLE_DROPDOWN)
expanded = false
[...]
Upvotes: 0
Reputation: 363975
You can use a condition inside the onExpandedChange
to avoid to expand the
ExposedDropdownMenuBox
. This callback is called when the user clicks on the ExposedDropdownMenuBox
.
You can also remove the trailingIcon
in this case.
Something like:
var isTitleEnabled by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
if(isTitleEnabled) {
expanded = !expanded
}
}
) {
TextField(
enabled = isTitleEnabled,
readOnly = true,
trailingIcon = {
if (isTitleEnabled){
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded,
)
}
},
Upvotes: 7