就我而言,我使用 OutlinedTextField 中的 TrailingIcon 来扩展 DropdownMenu。如果使用,单击 TrailingIcon - DropdownMenu 将展开,但 OutlinedTextField 将不会聚焦。另外,当使用单击 OutlinedTextField 时 - DropdownMenu 将不会展开,但 OutlinedTextField 将获得焦点。
@Composable
fun DownMenuTextField(
@StringRes titleId: Int,
selectedText: String,
suggestions: List<String>,
onValueChange: (String) -> Unit
) {
var expanded by remember { mutableStateOf(false) }
var textFieldSize by remember { mutableStateOf(Size.Zero) }
val icon = if (expanded) Icons.Filled.ArrowDropUp else Icons.Filled.ArrowDropDown
Column {
OutlinedTextField(
value = selectedText,
readOnly = true,
onValueChange = { onValueChange(it) },
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
textFieldSize = coordinates.size.toSize()
},
label = {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = stringResource(titleId),
style = MaterialTheme.typography.body2
)
}
},
trailingIcon = {
Icon(icon, "contentDescription",
Modifier.focusable(false)
.clickable { expanded = !expanded })
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.width(with(LocalDensity.current) { textFieldSize.width.toDp() })
) {
suggestions.forEach { label ->
DropdownMenuItem(onClick = {
onValueChange(label)
expanded = false
}) {
Text(text = label)
}
}
}
}
}
点击尾随图标:
单击 OutlinedTextField:
当用户点击 TrailingIcon 或 OutlinedTextField 时如何操作 - 始终将聚焦 OutlinedTextField 并且展开 DropdownMenu
最佳答案
您可以在 TextField
获得焦点后展开下拉菜单,onFocusChanged
修饰符对此很有用。
然后在 onDismissRequest
中或选择该项目时,您可以使用 LocalFocusManager
清除焦点。
有一点与您的问题无关。我建议您始终使用修饰符
作为最后一个参数:在这种情况下,您不需要在末尾添加逗号,这样可以更轻松地添加新的/删除不必要的修饰符
val options = listOf("Option 1", "Option 2", "Option 3", "Option 4", "Option 5")
var expanded by remember { mutableStateOf(false) }
var selectedOption by remember { mutableStateOf(options[0]) }
val icon = if (expanded) Icons.Filled.ArrowDropUp else Icons.Filled.ArrowDropDown
val focusManager = LocalFocusManager.current
Column {
OutlinedTextField(
value = selectedOption,
readOnly = true,
onValueChange = {},
trailingIcon = {
Icon(icon, null)
},
modifier = Modifier
.fillMaxWidth()
.onFocusChanged {
expanded = it.isFocused
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = {
expanded = false
focusManager.clearFocus()
},
modifier = Modifier
.fillMaxWidth()
) {
options.forEach { label ->
DropdownMenuItem(onClick = {
selectedOption = label
expanded = false
focusManager.clearFocus()
}) {
Text(text = label)
}
}
}
}
结果:
关于android - 如何使用 TrailingIcon 同步 OutlinedTextField 上的焦点? - Android Jetpack 撰写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69143424/