Autocomplete
A text field that suggests matching options while the user types.
- Category: Selection and input
- API status: Stable
- Compose APIs:
ExposedDropdownMenuBox,ExposedDropdownMenuAnchorType.PrimaryEditable,ExposedDropdownMenuDefaults - Interactive page: https://m3e.ljzapps.app/#components/autocomplete
When to use
Use an editable exposed dropdown when people choose from a long list that they can filter by typing. For short lists use a read only exposed dropdown instead.
Open the menu when the text changes and filter the options. Close it when an option is chosen.
Playground
The interactive page has a playground with live property controls for this component and generated code.
Examples
Filter countries
Type to narrow the list.
var text by remember { mutableStateOf("") }
var expanded by remember { mutableStateOf(false) }
val options = Countries.filter { it.contains(text, ignoreCase = true) }
ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) {
OutlinedTextField(
value = text,
onValueChange = {
text = it
expanded = true
},
label = { Text("Country") },
singleLine = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
)
if (options.isNotEmpty()) {
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
options.forEach { option ->
DropdownMenuItem(
text = { Text(option) },
onClick = {
text = option
expanded = false
},
)
}
}
}
}
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
expanded / onExpandedChange | Boolean / (Boolean) -> Unit | Menu state. | |
menuAnchor type | ExposedDropdownMenuAnchorType | PrimaryNotEditable | Use PrimaryEditable for typing. |
options | List<String> | Filtered by the text field value. |
Guidelines
Do:
- Allow free text if the list is not complete.
- Highlight the matching part of the options.
Don't:
- Do not open the menu when there are no matches.
- Do not require a selection unless it is necessary.
Accessibility
- Arrow keys move through the suggestions, Enter selects and Escape closes.
- Announce the number of matching options.