You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose:Row内循环元素均分空间异常问题求助

问题原因

你的代码存在两个核心问题,导致仅显示单个元素:

  1. 多余的内部Row嵌套:每个BottomMenuItem里都套了一个无约束的Row,而内部Box的Modifier.weight(1f)会强制这个内部Row占满外层BottomMenu中Row的全部宽度,后续的BottomMenuItem直接被挤出屏幕。
  2. 权重设置位置错误:weight属性必须作用在同一Row/Column的直接子元素上才能实现空间均分,你把weight放在了嵌套的Box上,外层Row无法识别这个权重分配规则。
修复方案
  1. 移除BottomMenuItem内部多余的Row,直接用Box作为根布局。
  2. 在BottomMenu的循环中,给每个BottomMenuItem添加Modifier.weight(1f),让外层Row将宽度均分给所有子项。
修改后的代码
@Composable
fun BottomMenu(
    items: List<BottomMenuContent>,
    modifier: Modifier = Modifier,
    activeHighlightColor: Color = Green,
    activeTextColor: Color = Color.White,
    inactiveTextColor: Color = Color.Black,
    initialSelectedItemIndex: Int = 0
) {
    var selectedItemIndex by remember {
        mutableStateOf(initialSelectedItemIndex)
    }
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier
            .fillMaxWidth()
            .background(Gray)
            .padding(4.dp)
    ) {
        items.forEachIndexed { index, item ->
            BottomMenuItem(
                modifier = Modifier.weight(1f), // 给每个Item添加权重
                item = item,
                isSelected = index == selectedItemIndex,
                activeHighlightColor = activeHighlightColor,
                activeTextColor = activeTextColor,
                inactiveTextColor = inactiveTextColor
            ) {
                selectedItemIndex = index
            }
        }
    }
}

@Composable
fun BottomMenuItem(
    modifier: Modifier = Modifier,
    item: BottomMenuContent,
    isSelected: Boolean = false,
    activeHighlightColor: Color = Green,
    activeTextColor: Color = Color.White,
    inactiveTextColor: Color = Color.Black,
    onItemClick: () -> Unit
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = modifier
            .clickable { onItemClick() }
            .background(if (isSelected) activeHighlightColor else Color.Transparent)
            .padding(top = 14.dp, bottom = 14.dp)
    ) {
        Text(
            text = item.title,
            color = if(isSelected) activeTextColor else inactiveTextColor
        )
    }
}
效果说明

修改后,外层Row会将宽度平均分配给所有BottomMenuItem,每个Item内部的Box会填满Item的全部空间,点击切换背景色的功能正常生效,同时支持任意数量的元素动态适配宽度。

内容的提问来源于stack exchange,提问作者CodingProfile

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:51:06