我正在尝试在 Jetpack Compose 中实现一个包含 2 列的网格 UI。
我的要求是
- 每个项目的宽度必须是父宽度的一半(减去内边距等)
- 高度必须相同,因此项目是正方形。
- 在其中我应该能够做其他事情,比如在
Column
中使用weight
这应该如下所示
<-- parent
width -->
____ ____
| | | |
|____| |____|
____ ____
| | | |
|____| |____|
... and more items
我已经通过下面的代码部分地实现了这一点,但是高度似乎并没有“发送”给 children 。
// can use this inside a Column or LazyColumn
@Composable
fun TileRow() {
Row(modifier = Modifier.fillMaxWidth()) {
Box(modifier = Modifier.weight(1f, fill = true).padding(10.dp)) {
TestTile()
}
Box(modifier = Modifier.weight(1f, fill = true).padding(10.dp)) {
TestTile()
}
}
}
@Composable
fun TestTile (){
Surface(
color = Color.Red,
modifier = Modifier
.layout { measurable, constraints ->
val placeable = measurable.measure((constraints))
//placeable.height = placeable.width // can't resize. height has a private setter
layout(placeable.width, placeable.width) {
placeable.place(x = 0, y = 0, zIndex = 0f)
}
}.fillMaxSize() // fills the width, but not height, likely due to above layout
){
Column {
Text(text = "item1")
Text(text = "item2 to fill",
modifier = Modifier
.weight(1f)) // this is gone when weight is added
Text(text = "item3")
}
}
}
这会创建以下 UI。
看起来 Surface
布局正确,因为下一个 Row
有空间。但是该列似乎没有占据全部高度。这也意味着列项的 weight()
不起作用。将 weight
修饰符添加到子列中,使它们消失。
如何解决上述问题,让 children 知道高度并达到预期的结果?
作为引用,我使用的是 Jetpack Compose alpha09
更新:我已经尝试使用 preferredHeight(IntrinsicSize.Max)
并且它似乎工作得更好,但它确实需要用 标记代码@ExperimentalLayout
所以如果有其他可用选项,最好不要使用它。
最佳答案
根据 TileRow 的宽度自行设置磁贴的约束:
layout { measurable, constraints ->
val tileSize = constraints.maxWidth / columnCount
val placeable = measurable.measure(constraints.copy(
minWidth = tileSize,
maxWidth = tileSize,
minHeight = tileSize,
maxHeight = tileSize,
))
layout(placeable.width, placeable.width) {
placeable.place(x = 0, y = 0, zIndex = 0f)
}
}
参见 LazyGrid一个完整的例子
关于android - 将可组合高度调整为与宽度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65611920/