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

Tower Guidev2

08/09/2022, 8:28 AM
Hi i am attempting to employ a
androidx.compose.material3.ExposedDropdownMenuBox
to implement an Autosuggest drop down list
i allow the user to enter a partial search string and then i fetch matching suggestions from my local Room database. this functionality all works as required (although I am not condident that my current solution is Best Practice) however my issue is that when I recieve the suggestions back from my database call i would like the drop down to expand programatically and i cannot see how to achieve this. is it possibly to programmatically expand an
ExposedDropdownMenuBox
?
Copy code
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Greeting(viewModel: MviViewModel<Reactionable<*>, Actionable>, names: List<String>) {
    val suggestions by remember { mutableStateOf(names) }
    var expanded by remember { mutableStateOf(true) }
    var selectedOptionText by remember { mutableStateOf("") }

    LaunchedEffect(key1 = selectedOptionText) {
        if (selectedOptionText.trim().length > 2) viewModel.send(Suggest(selectedOptionText))
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {

        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = { expanded = !expanded },
        ) {
            TextField(
                value = selectedOptionText,
                onValueChange = {
                    selectedOptionText = it

                },
                label = { Text("Label") },
                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                colors = ExposedDropdownMenuDefaults.textFieldColors(),
            )

            if (suggestions.isNotEmpty()) {
                ExposedDropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false },
                ) {
                    suggestions.forEach { selectionOption ->
                        DropdownMenuItem(
                            text = { Text(selectionOption) },
                            onClick = {
                                selectedOptionText = selectionOption
                                expanded = false
                            }
                        )
                    }
                }
            }
        }
    }
}
16 Views