下拉菜单 clips/shrinks 项 Jetpack Compose

Drop down menu clips/shrinks items Jetpack Compose

我正在创建一个下拉菜单,其中的项目包含一个文本元素和一个图标(中间有一个 spacer);但只有第一个文本被完整显示。该图标仅在有另一个项目占用更多 space.

时可见

@Preview(showSystemUi = true)
@Composable
fun MyScreen() {
    Box(Modifier.fillMaxSize(), Alignment.Center) {

        Box() {
            var expanded by remember { mutableStateOf(false) }

            IconButton(onClick = { expanded = !expanded }) {
                Icon(imageVector = Icons.Default.MoreVert, contentDescription = null)
            }

            DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
                MyMenuItem("item 1")           // Icon visible
                MyMenuItem("item 2")           // Icon visible
                MyMenuItem("item 3 long text") // Icon width shrunk to 0
                MyMenuItem("item 4 long te")   // Icon visible but shrunk
            }

        }
    }
}

@Composable
fun MyMenuItem(text: String) {
    DropdownMenuItem(onClick = { }) {
        Text(text)
        Spacer(modifier = Modifier.weight(1f))
        Icon(imageVector = Icons.Default.Check, contentDescription = null) // <-- Icon
    }
}

注:

  1. 我也试过用 Row()Surface() 代替 DropdownMenuItem() 但结果是相似的。
  2. MyMenuItem() 作品赋予宽度;但我希望它根据内容自动调整大小。

一般来说,要创建这样的布局,您只需将 Modifier.weight(1f) 应用到您的 Text

您的 Column 还需要 Modifier.width(IntrinsicSize.Max) 以使宽度等于最宽的项目,但在您的情况下它已经内置于 DropdownMenu.

但是随后 this bug 弹出,这不允许您使用 Icon 正确调整 MyMenuItem 的大小。请打个星标以引起更多关注。

作为此错误修复之前的临时解决方案,您可以手动指定图标的大小,如下所示:

// copied from the source code as it's internal
const val MaterialIconDimension = 24f

@Composable
fun MyMenuItem(text: String) {
    DropdownMenuItem(
        onClick = { }
    ) {
        Text(text, Modifier.weight(1f))
        Icon(
            imageVector = Icons.Default.Check, 
            contentDescription = null, 
            modifier = Modifier.size(MaterialIconDimension.dp)
        )
    }
}

结果: