13

I'm working on a Jetpack Compose (1.3.0-beta03) and Material3 (1.0.0-beta03) app.

I'd like to show the user a simple dropdown with different languages, and the following code isn't very different from what you'll find online:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Settings() {
    val languages = listOf("it", "en", "de", "ro", "fr", "es")

    var expanded by remember { mutableStateOf(false) }
    var selectedOptionText by remember { mutableStateOf("ro") }

    ExposedDropdownMenuBox(
        modifier = Modifier.padding(16.dp),
        expanded = expanded,
        onExpandedChange = { expanded = !expanded },
    ) {
        TextField(
            readOnly = true,
            value = selectedOptionText,
            onValueChange = {},
            label = { Text(stringResource(R.string.default_reading_language)) },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            colors = ExposedDropdownMenuDefaults.textFieldColors(),
            modifier = Modifier.fillMaxWidth()
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            languages.forEach {
                DropdownMenuItem(
                    text = { Text(it) },
                    onClick = {
                        selectedOptionText = it
                        expanded = false
                    }
                )
            }
        }
    }
}

Running on the emulator show the Textfield correctly, but if I click on it, does not show the dropdown. It also set the correct option ("ro"), as expected.

No clue on how to fix this.

Any help is greatly appreciated.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Valerio
  • 3,297
  • 3
  • 27
  • 44
  • have you tried this? https://stackoverflow.com/questions/67111020/exposed-drop-down-menu-for-jetpack-compose – android Oct 04 '22 at 09:50
  • @android I've already checked out that. The accepted answer is almost identical to my code. There is something I should point my attention to? – Valerio Oct 04 '22 at 10:04

1 Answers1

28

With M2 your code works well.

With M3 you have to pass the menuAnchor modifier to the TextField (it was introduced with material3 1.0.0-beta03):

ExposedDropdownMenuBox(
    modifier = Modifier.padding(16.dp),
    expanded = expanded,
    onExpandedChange = { expanded = !expanded },
) {
   TextField(
        //...
        modifier = Modifier.menuAnchor()
    )
    ExposedDropdownMenu(
        /* .. */
    ) { /*..  */ }
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841