Last active
January 14, 2023 00:43
-
-
Save Wavesonics/e3d5c122b7aed3a6114c33a2dcb8719c to your computer and use it in GitHub Desktop.
A Dropdown box composable
This file contains hidden or 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 <T> DropDown( | |
modifier: Modifier = Modifier, | |
padding: Dp = 16.dp, | |
items: List<T>, | |
defaultIndex: Int = 0, | |
onValueChanged: (T) -> Unit | |
) { | |
var selectedIndex by remember { mutableStateOf(defaultIndex) } | |
var itemsExpanded by remember { mutableStateOf(false) } | |
BoxWithConstraints( | |
modifier = modifier | |
.background(Color.LightGray) | |
.border(1.dp, MaterialTheme.colors.onBackground) | |
.clickable(onClick = { itemsExpanded = true }) | |
) { | |
Text( | |
items[selectedIndex].toString(), | |
modifier = Modifier.padding( | |
PaddingValues(start = padding, end = padding * 2, top = padding, bottom = padding) | |
).wrapContentWidth() | |
) | |
Icon( | |
Icons.Rounded.ArrowDropDown, | |
"Drop Down Menu", | |
modifier = Modifier.align(Alignment.CenterEnd) | |
) | |
DropdownMenu( | |
expanded = itemsExpanded, | |
onDismissRequest = { itemsExpanded = false }, | |
) { | |
items.forEachIndexed { index, item -> | |
DropdownMenuItem(onClick = { | |
selectedIndex = index | |
itemsExpanded = false | |
onValueChanged(items[index]) | |
}) { | |
Text(text = item.toString()) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment