自动完成可组合

问题描述 投票:0回答:1

我正在基于这个答案制作一个自动完成可组合函数:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AutoComplete(
    labelText: String,
    options: List<String>,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
) {
    var expanded = value.length > 2
    val filterOpts = options.filter { it.contains(value, ignoreCase = true) }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { expanded = !expanded }) {
        TextField(
            label = { Text(text = labelText) },
            readOnly = true,
            value = value,
            onValueChange = onValueChange,
            colors = ExposedDropdownMenuDefaults.textFieldColors(),
            modifier = modifier.menuAnchor(),
            keyboardOptions = keyboardOptions,
        )
        if (!filterOpts.isEmpty()) {
            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }) {
                filterOpts.forEach { option ->
                    DropdownMenuItem(
                        text = { Text(text = option) },
                        onClick = {
                            onValueChange(option)
                            expanded = false
                        }
                    )
                }
            }
        }
    }
}

我这样使用它:

        val names = listOf("Tony Stark", "Steve Rogers", "Bruce Banner", "Natasha Romanoff")
        var name by remember {
            mutableStateOf("")
        }

        AutoComplete(
            labelText = "Name",
            options = names,
            value = name,
            onValueChange = { name = it },
        )

当我运行此程序并关注“名称”字段时,我在模拟器中没有看到屏幕键盘,并且在笔记本电脑上键入也不起作用。我缺少什么?如何让孩子

TextField
聚焦以便系统自动显示键盘?

android user-interface autocomplete android-jetpack-compose
1个回答
0
投票

如果您想要键盘,您可能不想设置

readOnly = true

另外,我不知道你想实现什么目的,但是即使选择了选项后,

var expanded = value.length > 2
也会保持下拉菜单打开。为了避免这种情况,您可以将
expanded
声明为常规记忆布尔值:

var expanded by remember { mutableStateOf(false) }

并且仅在

TextField
中的值更改后检查输入长度:

onValueChange = {
    expanded = value.length > 2
    onValueChange(it)
},
© www.soinside.com 2019 - 2024. All rights reserved.