编辑:Google 现已修复此问题:https://issuetracker.google.com/issues/197254738.希望它能够尽快进入 JC 版本!
问题已有几个月了,但最近遇到了这个问题,因此其他人可能会发现这些解决方案很有用:
解决方案 0(最快)
没有分隔线。例如:
TabRow(
selectedTabIndex = ...,
modifier = Modifier.height(100.dp).fillMaxWidth(),
divider = {}
) { /* content here */ }
解决方案 1
由于 TabRow 只是一个容器,因此不要在其修饰符中指定 height。如果您希望它具有自定义高度,请确保每个选项卡都明确指定其高度。例如:
var selectedTabIndex by remember { mutableStateOf(0) }
TabRow(
selectedTabIndex = selectedTabIndex,
modifier = Modifier.fillMaxWidth(), // Don't specify the TabRow's height!
backgroundColor = Colors.White
) {
listOf("Hello", "World").forEachIndexed { i, text ->
Tab(
selected = selectedTabIndex == i,
onClick = { selectedTabIndex = i },
modifier = Modifier.height(50.dp), // Specify the Tab's height instead
text = { Text(text) }
)
}
}
解决方案 2
强制分隔线仅在布局底部绘制。这与默认指标实现一致。
TabRow(
selectedTabIndex = ...,
modifier = Modifier.height(100.dp).fillMaxWidth(),
backgroundColor = Colors.White,
divider = { TabRowDefaults.Divider(Modifier.wrapContentSize(Alignment.BottomStart)) },
) { /* content here */ }
说明
从源代码here和here来看,默认分隔线的高度为1dp。但是,OP 看到的是灰色背景,因为分隔线正在绘制整个 TabRow!
当您在 TabRow 上指定 height 约束时,约束将传递到分隔符(源代码 here)。因此,分隔线占据了 TabRow 的整个高度——在 OP 的情况下,分隔线是透明的灰色,因此它使 TabRow 看起来是灰色的。上述解决方案有几种不同的方法来解决问题:
- 移除分隔线即可解决问题!
- TabRows 包装它们的选项卡,因此另一种解决方案是通过指定选项卡的高度而不是 TabRow 的高度来指定 TabRow 的高度。
- 这会强制分隔线忽略 TabRow 的高度约束,而是在 TabRow 中的 BottomStart 位置以正确的高度绘制自身。