How to make JetpackCompose DropDownMenu pop up item wider?

Viewed 719

I have a Dropdown Composable View that can use as a selection.

@Composable
fun <T> DropdownDemo(modifier: Modifier, items: List<T>, selected: MutableState<T>) {
    var expanded by remember { mutableStateOf(false) }
    Box(modifier = modifier.fillMaxWidth()) {
        Text(
            selected.value.toString(),
            modifier = Modifier
                .background(Color.LightGray)
                .fillMaxWidth()
                .clickable(
                    onClick = { expanded = true })
                .padding(16.dp, 0.dp)
        )
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.fillMaxWidth(),
        ) {
            items.forEachIndexed { index, select ->
                DropdownMenuItem(
                    onClick = {
                        selected.value = items[index]
                        expanded = false
                    },
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text(text = select.toString(), modifier = Modifier.fillMaxWidth())
                }
            }
        }
    }
}

When no click on, the Text shown is fill up the entire width. However, when clicked and expanded, the pop up cannot be expanded fully, even though I set Modifier.fillMaxWidth() in the DropdownMenu and DropdownMenuItem.

enter image description here

How can I get the pop up of the DropdownMenu wider?

1 Answers

You can copy DropdownMenuItemContent and modify it to allow passing in the min and max width

@Composable
fun AdjustableWidthDropdownMenuItem(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    contentPadding: PaddingValues = MenuDefaults.DropdownMenuItemContentPadding,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    minWidth: Dp = 112.dp,
    maxWidth: Dp = 280.dp,
    content: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = modifier
            .clickable(
                enabled = enabled,
                onClick = onClick,
                interactionSource = interactionSource,
                indication = rememberRipple(true)
            )
            .fillMaxWidth()
            .sizeIn(
                minWidth = minWidth,
                maxWidth = maxWidth,
                minHeight = 48.dp
            )
            .padding(contentPadding),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val typography = MaterialTheme.typography
        ProvideTextStyle(typography.subtitle1) {
            val contentAlpha = if (enabled) ContentAlpha.high else ContentAlpha.disabled
            CompositionLocalProvider(LocalContentAlpha provides contentAlpha) {
                content()
            }
        }
    }
}
Related