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

Android Compose:可滚动Row内Modifier宽度异常问题排查

问题:水平滚动Row中的Compose卡片分割线宽度为0不显示

你在构建水平滚动Row包含卡片的布局时遇到了问题:单独显示TestCard时分割线正常显示,但将卡片放入水平滚动Row后,分割线存在但宽度为0,无法看到。

你的代码如下:

TestCard 代码

@Composable
fun TestCard(
  name: String
) {
  Column(
    modifier = Modifier
      .background(MaterialTheme.colors.surface)
      .padding(12.dp),
    horizontalAlignment = Alignment.Start
  ) {
    Text(text = name, style = Typography.h4.bold.black)
    Spacer(modifier = Modifier.height(8.dp))
    Divider(color = Color.Black) //在Row中不显示
    Spacer(modifier = Modifier.height(8.dp))
    Divider(modifier = Modifier.fillMaxWidth(), color = Color.Black) //在Row中不显示
    Spacer(modifier = Modifier.height(8.dp))
    Text(text = "Other text", style = Typography.h4.bold.black)
  }
}

TestComponent 代码

@Composable
fun TestComponent() {

  val scrollState = rememberScrollState()
  val names = listOf("Martha", "Erik","Steve","Roy","Pete")

  Column(
    modifier = Modifier
      .fillMaxWidth()
      .background(MaterialTheme.colors.primary),
    horizontalAlignment = Alignment.Start
  ) {
    Row(Modifier.horizontalScroll(scrollState), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
      names.forEach { name ->
        TestCard(name)
      }
    }
  }
}

问题原因

在水平滚动的Row中,子元素的宽度默认是**内容包裹(wrapContent)**模式。你的TestCard内部的Column没有明确的宽度约束,它的宽度会被内部的Text内容撑开。而Divider的fillMaxWidth()是相对于父容器Column的宽度,但此时Column没有确定的宽度基准,导致Divider无法计算出有效宽度,最终宽度为0。

单独显示TestCard时,Column的父容器是屏幕宽度,fillMaxWidth()能获取到明确的宽度约束,因此分割线正常显示。


最优解决方案

不需要用onSizeChanged手动跟踪宽度,推荐使用**固有尺寸(Intrinsic Size)**来解决这个问题:给TestCard的Column添加.width(IntrinsicSize.Max)修饰符,让Column根据内部最宽的内容自动确定自身宽度,这样Divider的fillMaxWidth()就能基于这个宽度生效。

修改后的TestCard代码:

@Composable
fun TestCard(
  name: String
) {
  Column(
    modifier = Modifier
      .background(MaterialTheme.colors.surface)
      .padding(12.dp)
      .width(IntrinsicSize.Max), // 新增:让Column根据内容自适应宽度
    horizontalAlignment = Alignment.Start
  ) {
    Text(text = name, style = Typography.h4.bold.black)
    Spacer(modifier = Modifier.height(8.dp))
    Divider(color = Color.Black) // 现在会自动撑满Column宽度
    Spacer(modifier = Modifier.height(8.dp))
    Divider(modifier = Modifier.fillMaxWidth(), color = Color.Black) // 同样正常显示
    Spacer(modifier = Modifier.height(8.dp))
    Text(text = "Other text", style = Typography.h4.bold.black)
  }
}

备选方案(固定宽度)

如果需要所有卡片保持统一宽度,不管内容长短,可以直接给Column设置固定宽度,比如.width(240.dp),这种方式适合需要统一布局风格的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:45:32