https://kotlinlang.org logo
#compose
Title
# compose
k

Kshitij Patil

12/10/2020, 6:27 PM
With these ~40 lines of code, I was able to build a fully functioning
AutoCompleteTextFIeld
. Power of Jetpack Compose 🔥
Copy code
@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.
🎉 7
c

codeslubber

12/10/2020, 7:10 PM
Adding a thread.. might be good in future to just make a one line statement then put the larger thing inside the thread… (suggestion)..
k

Kshitij Patil

12/10/2020, 7:31 PM
Yeah I was going to. I had read your comment earlier but forgot to do 😅
👍🏻 1
v

Val Salamakha

12/10/2020, 9:19 PM
field.isBlank() should be change to field.text.isNotBlank() as unresolved reference because of receiver type mismatch: public fun CharSequence.isBlank(): Boolean defined in kotlin.text (Compose 1.0.0-alpha08)
c

codeslubber

12/10/2020, 9:24 PM
@Kshitij Patil thanks for posting, really great…
k

Kshitij Patil

12/10/2020, 9:30 PM
@Val Salamakha oh sorry, I have an extension function on TextFieldValue which returns
field.text.isBlank()
will update the gist
v

Val Salamakha

12/10/2020, 10:25 PM
@Kshitij Patil From my point field.text.isNotBlank() would look better than !field.text.isBlank()