首页 > 解决方案 > Android撰写约束布局问题

问题描述

撰写版本:1.0.0-beta04.

约束布局组合版本:1.0.0-alpha05

可组合:

@Composable
fun comp1() {
    Surface(Modifier
        .fillMaxWidth()
        .height(50.dp), color = Color.Red) {

        ConstraintLayout(Modifier.fillMaxSize()) {
            val guide_line = createGuidelineFromAbsoluteRight(.2f)
            val (icon_ref, box_ref, spacer_ref) = createRefs()
            
            Icon(Icons.Filled.Search, null,
                modifier = Modifier.constrainAs(icon_ref) {
                    absoluteLeft.linkTo(guide_line)
                    absoluteRight.linkTo(parent.absoluteRight)
                    top.linkTo(parent.top)
                    bottom.linkTo(parent.bottom)
                }
            ) 

            Box(Modifier
                .background(Color.Blue)
                .fillMaxSize()
                .constrainAs(box_ref) {
                    absoluteLeft.linkTo(parent.absoluteLeft)
                    absoluteRight.linkTo(guide_line)
                    top.linkTo(parent.top)
                    bottom.linkTo(parent.bottom)
                }) {}

            Spacer(Modifier
                .background(Color.Yellow)
                .width(2.dp)
                .fillMaxHeight()
                .constrainAs(spacer_ref) {
                    absoluteRight.linkTo(guide_line)
                })
        }
    }

}

预览:

在此处输入图像描述

在此处输入图像描述

如您所见,这些项目并没有像预期的那样受到限制。view_based 中的视图ConstraintLayout不会在屏幕之外绘制,除非约束被弄乱或者是故意的。

标签: androidandroid-jetpack-compose

解决方案


Box可组合中删除fillMaxSize()修饰符并应用约束width = Dimension.fillToConstraints

就像是:

Surface(Modifier
    .fillMaxWidth()
    .height(50.dp), color = Color.Red) {

    ConstraintLayout(Modifier.fillMaxSize()) {
        val guide_line = createGuidelineFromAbsoluteRight(.2f)
        val (icon_ref, box_ref, spacer_ref) = createRefs()

        Icon(Icons.Filled.Search, null,
            modifier = Modifier.constrainAs(icon_ref) {
                start.linkTo(guide_line)
                end.linkTo(parent.end)
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
            }
        )

        Box(contentAlignment=Alignment.CenterStart,
            modifier = Modifier
            .background(Color.Blue)
            .fillMaxHeight()
            .constrainAs(box_ref) {
                start.linkTo(parent.start)
                end.linkTo(guide_line)
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
                width = Dimension.fillToConstraints //ADD THIS
            }) {

            Text(text = "Text ", color = Yellow)
        }

        Spacer(Modifier
            .background(Color.Yellow)
            .width(2.dp)
            .fillMaxHeight()
            .constrainAs(spacer_ref) {
                end.linkTo(guide_line)
            })
    }
}

在此处输入图像描述


推荐阅读