Dropdown Button/Wheel Picker/Spinner in Jetpack Compose
Asked Answered
I

2

9

Is there any standard implementation in Jetpack Compose for visual component like Spinner/Wheel Picker or Dropdown Button?

Iambic answered 4/6, 2021 at 18:43 Comment(0)
G
14

You can use a Button with a DropdownMenu.
Something like:

var expanded by remember { mutableStateOf(false) }
val suggestions = listOf("Item1", "Item2", "Item3")

Button(onClick = { expanded = !expanded }){
    Text ("DropDown")
    Icon(
        imageVector = Icons.Filled.ArrowDropDown,
        contentDescription = null,
    )
}
DropdownMenu(
    expanded = expanded,
    onDismissRequest = { expanded = false },
) {
    suggestions.forEach { label ->
        DropdownMenuItem(onClick = {
            expanded = false
            //do something ...
        }) {
            Text(text = label)
        }
    }
}

enter image description here enter image description here

Gudrunguelderrose answered 4/6, 2021 at 19:33 Comment(1)
I recommend wrapping the DropdownMenu in a Column or a BoxSolorzano
M
2

Yes, as @kc.dev commented, the button and the dropdownmenu better be in a box like the following. Otherwise, the popup will be in undesired position.

var expanded by remember { mutableStateOf(false) }
val suggestions = listOf("Item1", "Item2", "Item3")

Box {
    Button(onClick = { expanded = !expanded }){
        Text ("DropDown")
        Icon(
            imageVector = Icons.Filled.ArrowDropDown,
            contentDescription = null,
        )
    }
    DropdownMenu(
        expanded = expanded,
        onDismissRequest = { expanded = false },
    ) {
        suggestions.forEach { label ->
            DropdownMenuItem(onClick = {
                expanded = false
                //do something ...
            }) {
                Text(text = label)
            }
        }
    }
}
Maremma answered 28/3, 2022 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.