I want to select a default value for my dropdown menu as soon as the component renders. Don't want it to set as a label instead I want one of the options from dropdown menu to be selected by default and then the user might change it according to his preference
I am doing something like this , it does sets the default value but then I am unable to change it by selecting from the dropdown
val inspectorList = searchViewModel.inspectors.collectAsState().value
var defaultSelectedInspector = ""
var selectedInspector by remember { mutableStateOf(defaultSelectedInspector)}
if (inspectorList?.isNotEmpty() == true) {
defaultSelectedInspector = inspectorList[0]
selectedInspector = defaultSelectedInspector
}
And this is my dropdown menu code
Box(modifier = Modifier.fillMaxWidth()) {
OutlinedTextField(
value = selectedInspector,
onValueChange = {},
enabled = false,
modifier = Modifier
.clickable { showInspectorDropdown = !showInspectorDropdown }
.onGloballyPositioned { coordinates ->
textFieldSize = coordinates.size.toSize()
},
colors = TextFieldDefaults.textFieldColors(
disabledTextColor = Color.DarkGray,
backgroundColor = Color.Transparent
),
trailingIcon = {Icon(imageVector = inspectorDropDownIcon, contentDescription = "")}
)
DropdownMenu(
expanded = showInspectorDropdown,
onDismissRequest = { showInspectorDropdown = false },
Modifier.width(with(LocalDensity.current) { textFieldSize.width.toDp() })
) {
inspectorList?.forEach { inspector ->
DropdownMenuItem(
onClick = {
showInspectorDropdown = false
selectedInspector = inspector
}) {
Text(text = inspector)
}
}
}
}
You can try something like:
val options = listOf("Option 1", "Option 2", "Option 3", "Option 4", "Option 5")
var expanded by remember { mutableStateOf(false) }
var selectedOptionText by remember { mutableStateOf(options[1]) }
// We want to react on tap/press on TextField to show menu
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
TextField(
readOnly = true,
value = selectedOptionText,
onValueChange = { },
label = { Text("Label") },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded
)
},
colors = ExposedDropdownMenuDefaults.textFieldColors()
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = {
expanded = false
}
) {
options.forEach { selectionOption ->
DropdownMenuItem(
onClick = {
selectedOptionText = selectionOption
expanded = false
}
) {
Text(text = selectionOption)
}
}
}
}