首页 > 解决方案 > Jetpack Compose 下拉菜单

问题描述

我有这个下拉列表,但尽管有 Modifier.fillMaxWidth(),它并没有填满所有的屏幕宽度。

顶部应用栏的主要区域横跨屏幕宽度,当我点击它时,我希望下拉菜单以与顶部应用栏相同的宽度展开。但是扩展的下拉菜单更窄。

如何更改它以填充最大屏幕宽度?

fun DropdownChildren(
    items: List<ChildUiModel>,
    chosenChild: ChildUiModel?,
    onChildChosen: (ChildUiModel) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    var selectedIndex by remember { mutableStateOf(0) }
    Box(modifier = Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.Center)) {
        Row(modifier = Modifier
            .fillMaxSize()
            .clickable(onClick = { expanded = true }),
            verticalAlignment = Alignment.CenterVertically) {
            ChildrenDropdownMenuItem(
                imageUrl = chosenChild?.profileImage?: "https://c8.alamy.com/comp/TBRA08/many-children-on-frame-border-illustration-TBRA08.jpg",
                    text = chosenChild?.name?: stringResource(id = R.string.all_children),
                    chosen = false)

        }

        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .fillMaxWidth()
                .requiredSizeIn(maxHeight = 500.dp)
        ) {
            items.forEachIndexed { index, child ->
                DropdownMenuItem(
                    modifier = Modifier
                        .fillMaxWidth()
                    .background(color = if (child.id == chosenChild?.id) appColors.secondary else appColors.primary),
                    onClick = {
                        expanded = false
                        selectedIndex = index
                        onChildChosen(items[selectedIndex])
                }) {
                    ChildrenDropdownMenuItem(
                        imageUrl = if (child.profileImage == null)
                            "https://pics.freeicons.io/uploads/icons/png/2793494581535699799-512.png"
                        else child.profileImage?: "https://pics.freeicons.io/uploads/icons/png/2793494581535699799-512.png",
                        text = child.name,
                        chosen = child.id == chosenChild?.id)

                }
            }
        }
    }
}

@Composable
fun ChildrenDropdownMenuItem(
    imageUrl: String,
    text: String,
    chosen: Boolean
){
    Row(modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically){
        Avatar(url = imageUrl)
        Text(text = text,
            style = AppTheme.typography.h4,
            color = if (chosen) appColors.primary else appColors.secondary)
    }
} ```

标签: androidandroid-jetpack-compose

解决方案


阅读DropdownMenu的源码,max是硬编码的,你可以复制源码,把宽度设置成你喜欢的值。


推荐阅读