Last active
April 3, 2023 10:06
-
-
Save Kshitij09/01ed382d395273dd0eac453003265ad9 to your computer and use it in GitHub Desktop.
AutoCompleteTextView implemented in Jetpack Compose.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is savedInstanceState ?