Kshitij Patil
12/10/2020, 6:27 PMAutoCompleteTextFIeld
. Power of 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.text.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))
})
)
}
}
}
}
You can find a gist here for future reference: https://gist.github.com/Kshitij09/01ed382d395273dd0eac453003265ad9
Any suggestion are welcome 🙂
One issue I found was with the cursor offsets. I need some way to move the cursor to the end on selecting an item from suggestion-list. I tried to do something with OffsetMap
but didn't work.codeslubber
12/10/2020, 7:10 PMKshitij Patil
12/10/2020, 7:31 PMVal Salamakha
12/10/2020, 9:19 PMcodeslubber
12/10/2020, 9:24 PMKshitij Patil
12/10/2020, 9:30 PMfield.text.isBlank()
will update the gistVal Salamakha
12/10/2020, 10:25 PM