Android Compose ConstraintLayout 问题

时间:2021-04-21 14:26:54

标签: android android-jetpack-compose

撰写版本:1.0.0-beta04

constraintlayout-compose 版本: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)
                })
        }
    }

}

预览:

enter image description here

enter image description here

如您所见,项目并没有像人们期望的那样受到限制。 view_based ConstraintLayout 中的视图不会绘制到屏幕之外,除非约束被搞砸了或者是故意的。

1 个答案:

答案 0 :(得分:0)

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) }) } }

类似于:

v7.0.0

enter image description here