Waf*_*_ck 13 android kotlin android-jetpack android-jetpack-compose
我用来LazyVerticalGrid显示项目列表。
LazyVerticalGrid(
cells = GridCells.Fixed(2),
modifier = Modifier.fillMaxSize(),
state = listState,
content = {
Box(modifier = boxModifier) {
ProductItemView(
item = items[index]
)
}
}
}
)
Run Code Online (Sandbox Code Playgroud)
如何调整所有项目的高度?或者我应该使用VerticalGrid() 之外的其他东西?
如果您为可组合项指定固定高度,则最终的可组合项可能不会显示子可组合项的某些部分,在您的情况下,它可能是Text可组合项。
第一个也是简单的方法是设置最小高度Modifier.heightIn(min = 200.dp),这可能会在可组合项下方或上方留下空间,具体取决于您的框对齐方式,如果您的可组合项高于 200.dp,它将具有与现在相同的效果,所以它不是或添加任何固定高度是不够的。
更好的方法是使用 onTextLayout 获取文本的行数和高度,以添加较少的行数作为填充,如下
@Composable
fun GridSnackCardWithTitle(
modifier: Modifier = Modifier,
snack: Snack,
) {
Column(
modifier = modifier
.heightIn(min = 200.dp)
.shadow(1.dp, shape = RoundedCornerShape(5.dp))
.background(Color.White),
) {
val density = LocalDensity.current.density
Image(
contentScale = ContentScale.None,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(8.dp))
.clickable { },
painter = rememberImagePainter(
data = snack.imageUrl,
builder = {
placeholder(drawableResId = R.drawable.placeholder)
}
),
contentDescription = null
)
Spacer(modifier = Modifier.height(4.dp))
var padding by remember { mutableStateOf(0.dp) }
Text(
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = padding),
text = "Snack ${snack.name}",
fontSize = 20.sp,
onTextLayout = {
val lineCount = it.lineCount
val height = (it.size.height / density).dp
println("lineCount: $lineCount, Height: $height")
padding = if (lineCount > 1) 0.dp else height
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
结果
| 归档时间: |
|
| 查看次数: |
4899 次 |
| 最近记录: |