【发布时间】:2021-01-07 11:53:58
【问题描述】:
我正在尝试在 Jetpack Compose 中实现具有 2 列的网格 UI。
我的要求是
- 每个项目的宽度必须是父宽度的一半(减去填充等)
- 高度必须相同,因此项目是正方形。
- 在这里面我应该能够做其他事情,比如在
Column中使用weight
应该如下所示
<-- parent
width -->
____ ____
| | | |
|____| |____|
____ ____
| | | |
|____| |____|
... and more items
我已经通过下面的代码部分实现了这一点,但是高度似乎没有“发送”给孩子们。
// 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 修饰符添加到列子项会使它们消失。
我该如何解决以上问题,让孩子们知道身高并达到预期的效果?
作为参考,我正在使用 Jetpack Compose alpha09
更新:我尝试过使用preferredHeight(IntrinsicSize.Max),它似乎效果更好,但它确实需要将代码标记为@ExperimentalLayout,所以如果有另一个代码,最好不要使用它选项可用。
【问题讨论】:
标签: android android-jetpack-compose