我一直在尝试使用 compose 实现以下布局:
为此,我创建了可组合:
@Preview(showBackground = true)
@Composable
fun element() {
ConstraintLayout(
modifier = Modifier.fillMaxWidth()
) {
val (checkbox, title, icon) = createRefs()
Text(
text = "This would be some text",
style = TextStyle(
color = Color.Black,
fontSize = 18.sp,
),
modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(checkbox.end)
end.linkTo(icon.start)
},
)
Checkbox(
checked = false,
modifier = Modifier.constrainAs(checkbox) {
top.linkTo(title.top)
bottom.linkTo(title.bottom)
start.linkTo(parent.start)
},
onCheckedChange = {},
)
Icon(
asset = Icons.Filled.Close,
modifier = Modifier
.constrainAs(icon) {
top.linkTo(title.top)
bottom.linkTo(title.bottom)
end.linkTo(parent.end)
}
)
}
}
但是,可组合的文本不会填满整个空间,并且 UI 看起来像:我尝试向
Text
添加修饰符可组合,如 Modifier..fillMaxWidth()
,但这会导致:我也尝试过使用带有水平链的约束集,但无济于事。我知道删除
end.linkTo(icon.start)
看起来这是可以实现的,但是当文本很长时,它会与删除图标重叠。我在这里想念什么?当我们说
TextView
时,如何获得与 View 系统中相同的结果的宽度为 0dp
?
最佳答案
使用 Dimension.fillToConstraints
:
A Dimension that spreads to match constraints. Links should be specified from both sides corresponding to this dimension, in order for this to work.
将此行添加到您的
Text
修饰符:width = Dimension.fillToConstraints
所以它变成:Text(
text = "This would be some text",
style = TextStyle(
color = Color.Black,
fontSize = 18.sp,
),
modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(checkbox.end)
end.linkTo(icon.start)
width = Dimension.fillToConstraints
},
)
关于android - 等价于约束布局 0dp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64313409/