等效于约束布局0dp

时间:2020-10-12 07:31:08

标签: android android-jetpack-compose

我一直在尝试通过compose实现以下布局:

enter image description here

为此,我创建了可组合对象:

@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如下所示: enter image description here

我尝试向Text之类的Modifier..fillMaxWidth()组合物中添加修饰符,但这导致:

enter image description here

我也尝试过使用带有水平链的约束集,但无济于事。我知道删除end.linkTo(icon.start)看起来是可以实现的,但是当文本很长时,它将与删除图标重叠。

我在这里想念什么?当我们说TextView的宽度为0dp时,如何获得与视图系统相同的结果?

1 个答案:

答案 0 :(得分:9)

使用Dimension.fillToConstraints

展开以匹配约束的尺寸。链接应该是 从与该尺寸对应的两侧指定 为此工作。

将此行添加到您的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
    },
)