I'm trying to implement a dropdown/autocomplete te...
# compose
p
I'm trying to implement a dropdown/autocomplete textfield. I'm doing it with an outlinedtextfield that makes a dropdown menu with suggestions appear when user writes text. It works... but when I press a key and a letter appears... the dropdown appears and removes the focus from the outlinedtextfield forzing the keyboard to dissapear and the user can't write more letters without pressing again on the outlinedtextfield. Can this be solved with an easy solution? everything I'm finding out is too much complex, like using FocusRequester etc... don't like it.
Copy code
@Composable
fun AutoCompleteTextField(
    modifier: Modifier = Modifier,
    suggestions: List<String>,
    label: String,
    readOnly: Boolean = false,
    onItemSelected: (String) -> Unit
) {
    var query by rememberSaveable { mutableStateOf("") }
    var expanded by rememberSaveable { mutableStateOf(false) }
    var textFieldSize by remember { mutableStateOf(Size.Zero) }

    val filteredSuggestions = suggestions.filter {
        it.contains(query, ignoreCase = true) || query.isBlank()
    }

    Column(modifier = modifier) {
        OutlinedTextField(
            value = query,
            onValueChange = {
                query = it
                expanded = true
            },
            label = { Text(label) },
            modifier = Modifier
                .fillMaxWidth()
                .onGloballyPositioned { coordinates ->
                    textFieldSize = coordinates.size.toSize()
                },
            trailingIcon = {
                Icon(
                    imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                    contentDescription = null,
                    modifier = Modifier.clickable { expanded = !expanded }
                )
            },
            readOnly = readOnly,
            singleLine = true
        )

        DropdownMenu(
            expanded = expanded && filteredSuggestions.isNotEmpty(),
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(with(LocalDensity.current) { textFieldSize.width.toDp() })
        ) {
            filteredSuggestions.forEach { suggestion ->
                DropdownMenuItem(
                    onClick = {
                        query = suggestion
                        expanded = false
                        onItemSelected(suggestion)
                    },
                    text = { Text(suggestion) }
                )
            }
        }
    }
}