我正在使用 jetpack compose + 约束设置基于列表的设计,但我面临约束链接的一些问题,因为当它链接到父级时它无法正常工作。
这是我的代码
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProductCard(product:ProductModel){
ElevatedCard(
onClick = { },
modifier = Modifier
.padding(start = 15.dp, end = 15.dp, top = 10.dp, bottom = 10.dp)
.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = Color.White,
)
) {
ConstraintLayout{
val (productImage,productName,productCategory,
productPrice,ratingPrice) = createRefs()
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(product.productImage)
.crossfade(true)
.build(),
contentDescription = null,
placeholder = painterResource(id = R.drawable.user),
contentScale = ContentScale.Crop,
modifier = Modifier
.constrainAs(productImage) {
start.linkTo(parent.start, margin = 10.dp)
top.linkTo(parent.top, margin = 15.dp)
end.linkTo(productName.start)
bottom.linkTo(parent.bottom)
}
.width(72.dp)
.height(72.dp)
)
Text(
modifier = Modifier
.constrainAs(productName) {
top.linkTo(productImage.top)
start.linkTo(productImage.end, margin = 10.dp)
end.linkTo(parent.end,margin = 10.dp)
width = Dimension.wrapContent
},
text = product.productName,
fontFamily = notoSansFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 16.sp,
)
Text(
modifier = Modifier
.constrainAs(productCategory) {
top.linkTo(productName.bottom, margin = 5.dp)
start.linkTo(productName.start)
width = Dimension.wrapContent
},
text = product.productCategory,
fontFamily = notoSansFontFamily,
fontWeight = FontWeight.Medium,
fontSize = 15.sp,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.constrainAs(ratingPrice){
top.linkTo(productCategory.bottom, margin = 5.dp)
start.linkTo(productName.start)
end.linkTo(parent.end)
width = Dimension.fillToConstraints
}
.background(Color.Blue)
) {
Text(
text = product.productPrice,
fontFamily = notoSansFontFamily,
fontWeight = FontWeight.Bold,
fontSize = 14.sp,
color = Color.White
)
Text(
text = "Rating : ${product.productRating}",
fontFamily = notoSansFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
color = Color.Yellow,
modifier = Modifier.background(Color.Red)
)
}
Inside Row 我更新了添加排列的代码,所有卡片的结果都不同。它非常直接Row应该是linkTo startOf ProductName和endOf Parent。不知道为什么每张卡的行为都不同。查看图像,它在物理设备和模拟器设备中渲染相同。
请尝试将
horizontalArrangement
参数添加到 Row
并确保 ConstraintLayout
使用 fillMaxWidth()
:
ConstraintLayout(
modifier = Modifier.fillMaxWidth() // add this line
) {
//...
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween, // add this line
modifier = Modifier.constrainAs(ratingPrice){
top.linkTo(productCategory.bottom, margin = 5.dp)
start.linkTo(productName.start)
end.linkTo(parent.end)
width = Dimension.fillToConstraints
}
.background(Color.Blue)
) {
//...
}
}
之后您必须重新配置您的
Text
可组合项。您可以使用如下组合确保文本左对齐:
Text(
modifier = Modifier
.constrainAs(productName) {
//...
width = Dimension.fillToConstraints
}
//...
,
textAlign = TextAlign.Start,
//...
}