问题描述
我想将 Image
的高度限制为 LazyRow
的高度,并将它们排成一行。我能够使用以下代码主要实现此布局:
package com.example.test
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.ConstraintLayout
import androidx.compose.foundation.layout.Dimension
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.dp
@Composable
fun test() {
ConstraintLayout {
val (image,row) = createRefs()
createVerticalChain(image,row)
ARow(modifier = Modifier.constrainAs(row) {
start.linkTo(image.end)
width = Dimension.fillToConstraints
})
aimage(modifier = Modifier.constrainAs(image) {
top.linkTo(row.top)
bottom.linkTo(row.bottom)
height = Dimension.fillToConstraints
})
}
}
@Composable
fun aimage(modifier: Modifier = Modifier) {
Image(
modifier = modifier,bitmap = imageResource(id = R.drawable.sample_ic),)
}
@Composable
fun ARow(modifier: Modifier = Modifier) {
LazyRow(modifier = modifier) {
items((0..10).toList()) {
Text(modifier = Modifier.padding(8.dp),text = "Item: $it")
}
}
}
尽管使用了 width = Dimension.fillToConstraints
和链,但仍会出现此问题。 This 是你想要克隆的仓库
解决方法
将您的 ConstraintLayout
设置为最大宽度,并向您的 ARow
添加结束约束:
ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
val (image,row) = createRefs()
createVerticalChain(image,row)
ARow(modifier = Modifier.constrainAs(row) {
start.linkTo(image.end)
end.linkTo(parent.end)
width = Dimension.fillToConstraints
})
AImage(modifier = Modifier.constrainAs(image) {
top.linkTo(row.top)
bottom.linkTo(row.bottom)
height = Dimension.fillToConstraints
})
}