Skip to content

Instantly share code, notes, and snippets.

@Wavesonics
Last active January 14, 2023 00:43
Show Gist options
  • Save Wavesonics/e3d5c122b7aed3a6114c33a2dcb8719c to your computer and use it in GitHub Desktop.
Save Wavesonics/e3d5c122b7aed3a6114c33a2dcb8719c to your computer and use it in GitHub Desktop.
A Dropdown box composable
@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