Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AutoCompleteTextView implemented in Jetpack Compose.
@Composable
fun AutoCompleteTextField(
initialText: String,
itemList: List<String>,
onQuery: (String) -> Unit,
onClearResults: () -> Unit,
modifier: Modifier = Modifier
) {
val (field, changeField) = savedInstanceState(saver = TextFieldValue.Saver) { TextFieldValue(text = initialText) }
LaunchedEffect(subject = field.text) {
if (!field.isBlank()) {
delay(1000L)
onQuery(field.text.trim())
}
}
LazyColumn(modifier = modifier.animateContentSize()) {
item {
TextField(
value = field,
onValueChange = {
changeField(it)
onClearResults()
},
maxLines = 1
)
}
if (itemList.isNotEmpty() && !field.isBlank()) {
items(itemList) { item ->
Text(
item,
modifier = Modifier
.padding(4.dp)
.clickable(onClick = {
changeField(TextFieldValue(item))
})
)
}
}
}
}
fun TextFieldValue.isBlank() = this.text.isBlank()
@Kshitij09

This comment has been minimized.

Copy link
Owner Author

@Kshitij09 Kshitij09 commented Dec 10, 2020

Compose version: 1.0.0-alpha07
Assuming that on querying the backend, earlier result list will be changed, thus a request to clear results is being made on TextField value changes

EDIT: Added TextFieldValue.isBlank() extension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment