我正在尝试实现一个公开的下拉组合,我可以在我的android jetpack组合应用的多个部分中使用它。每当我从dropdownMenu中选择一个项目时,selectedOption就会在组合中设置,并分配给显示正确项目的文本字段值。但是,显示结果的文本字段的onValueChange事件没有被触发。这导致状态在我的应用的viewmodel层中没有被更新。遵循我的可组合代码。
// ExposedDropdownComposable.kt
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PlantExposedSelect(
options: List<String>,
optionSelected: String,
label: String,
onOptionSelected: (String) -> Unit,
onFocusChange: (FocusState) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
var selectedOption by remember { mutableStateOf(optionSelected) }
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = {
expanded = !expanded
}
) {
TextField(
readOnly = true,
value = selectedOption,
onValueChange = onOptionSelected
label = { Text(label) },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded
)
},
colors = ExposedDropdownMenuDefaults.textFieldColors(),
modifier = Modifier
.fillMaxWidth()
.onFocusChanged {
onFocusChange(it)
},
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = {
expanded = false
}
) {
options.forEach { selectOption ->
DropdownMenuItem(
onClick = {
selectedOption = selectOption
expanded = false
Log.e("selectEdoption", selectedOption)
}
) {
Text(text = selectOption)
}
}
}
}
}
这是我在AddPlantsScreen中使用可组合函数的代码
PlantExposedSelect(
options = options,
optionSelected = lightState.text,
label = lightState.hint,
onOptionSelected = {
Log.e("eventValue", it)
viewModel.onEvent(AddEditPlantEvent.EnteredLight(it))
},
onFocusChange = {
viewModel.onEvent(AddEditPlantEvent.ChangedLightFocus(it))
},
)
如何使dropdownItem的onClick事件触发显示selectedOption的Textfield的onValueChange事件。
2条答案
按热度按时间2nbm6dog1#
您只需在
DropdownMenuItem
的onClick
参数中调用onOptionSelected
,而不用使用onValueChange
。类似于:
chhqkbe12#
您可以像这样提升选中的选项状态,
并将
PlantExposedSelect
中的selectedOption
替换为optionSelected
。完整代码供参考