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() |
What is savedInstanceState ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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