【问题标题】:Equivalent of constraint layout 0dp等价于约束布局 0dp
【发布时间】:2021-01-26 12:06:34
【问题描述】:

我一直在尝试使用 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 的宽度是0dp 时,如何获得与视图系统中相同的结果?

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    使用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
        },
    )
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    相关资源
    最近更新 更多