Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto complete text view in compose

I want to create an auto complete text view in compose, and I created a composable that contains a TextField and a DropDown menu. The issue I'm seeing with this solution is that when the drop down menu is expanded the text field is no longer actionable, I can't type any text in it. Any suggestions on how to address this? The code is below

@Composable
fun AutoCompleteText(
    value: String,
    onValueChange: (String) -> Unit,
    onOptionSelected: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: @Composable (() -> Unit)? = null,
    suggestions: List<String> = emptyList()
) {
    Column(modifier = modifier) {
        OutlinedTextField(
            value = value,
            onValueChange = { text -> if (text !== value) onValueChange(text) },
            modifier = Modifier.fillMaxWidth(),
            label = label,
        )
        DropdownMenu(
            expanded = suggestions.isNotEmpty(),
            onDismissRequest = {  },
            modifier = Modifier.fillMaxWidth()
        ) {
            suggestions.forEach { label ->
                DropdownMenuItem(onClick = {
                    onOptionSelected(label)
                }) {
                    Text(text = label)
                }
            }
        }
    }
}
like image 279
Francesc Avatar asked Apr 25 '26 05:04

Francesc


1 Answers

DropdownMenu has a property called PopupProperties that you can use to disable focusability. This should allow you to be able to continue typing in to the OutlinedTextField:

OutlinedTextField(
  value = value,
  onValueChange = { text -> if (text !== value) onValueChange(text) },
  modifier = Modifier.fillMaxWidth(),
  label = label,
)
DropdownMenu(
  expanded = suggestions.isNotEmpty(),
  onDismissRequest = {  },
  modifier = Modifier.fillMaxWidth(),
  // This line here will accomplish what you want
  properties = PopupProperties(focusable = false)
) {
  suggestions.forEach { label ->
    DropdownMenuItem(onClick = {
      onOptionSelected(label)
    }) {
      Text(text = label)
    }
  }
}
like image 62
ariets Avatar answered Apr 26 '26 22:04

ariets