Skip to content

Instantly share code, notes, and snippets.

@JyotimoyKashyap
Last active April 13, 2025 06:05
Show Gist options
  • Select an option

  • Save JyotimoyKashyap/e002ff04d5371c6a0a068392239e291e to your computer and use it in GitHub Desktop.

Select an option

Save JyotimoyKashyap/e002ff04d5371c6a0a068392239e291e to your computer and use it in GitHub Desktop.
Custom Reusable Widgets
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun <T : DropdownMenuItem> DropdownItemSelector(
preSelectedIndex: Int = 0,
dropdownLabel: String,
menuItemList: List<T>,
onMenuItemChange: (T) -> Unit = {}
) {
var dropDownExpanded by remember { mutableStateOf(false) }
var selectedMenuItem by remember { mutableStateOf(menuItemList.first()) }
LaunchedEffect(preSelectedIndex) {
selectedMenuItem = menuItemList[preSelectedIndex]
}
AppTheme {
Text(
text = dropdownLabel,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(MaterialTheme.spacing.extraSmall))
ExposedDropdownMenuBox(
expanded = dropDownExpanded,
onExpandedChange = { dropDownExpanded = !dropDownExpanded }
) {
TextField(
value = selectedMenuItem.name,
onValueChange = {},
modifier = Modifier
.fillMaxWidth()
.menuAnchor(MenuAnchorType.PrimaryNotEditable),
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = dropDownExpanded)
},
leadingIcon = {
Icon(
imageVector = IconUtil.createImageVector(selectedMenuItem.icon),
contentDescription = null,
modifier = Modifier.size(ButtonDefaults.IconSize)
)
},
readOnly = true,
singleLine = true,
)
ExposedDropdownMenu(
expanded = dropDownExpanded,
onDismissRequest = { dropDownExpanded = false },
) {
menuItemList.forEach { option ->
DropdownMenuItem(
text = {
Text(
text = option.name,
style = MaterialTheme.typography.bodyLarge
)
},
onClick = {
selectedMenuItem = option
dropDownExpanded = false
onMenuItemChange(option)
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
leadingIcon = {
Icon(
imageVector = IconUtil.createImageVector(option.icon),
contentDescription = null
)
},
trailingIcon = {
if (option.id == selectedMenuItem.id) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = null
)
}
}
)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment