Jetpack Compose 之 ConstraintLayout

100 阅读1分钟

ConstraintLayout 相比前面的布局组件来说可以减少布局的嵌套, 但是在使用ConstarintLayout 的时候需要引入相对应的依赖。

implementation "androidx.constraintlayout:constraintlayout-compose:1.0.0-beta02"

如何使用

  1. 通过 createRefscreateRefFor 创建引用,每一个组件需要有一个引用
  2. 通过 Modifier.constrainAs 关联引用
  3. 在 constrainAs 的 body 块中使用 linkTo 、centerVerticallyTo等设置约束
  4. parent 是默认的父组件的引用,可以直接使用
ConstraintLayout {
val (head, name, phone) = createRefs ()
    Icon(
        imageVector = Icons.Default.Person,
        contentDescription = null,
        modifier = Modifier
            .size(50.dp)
            .constrainAs(head) {
start.linkTo(parent.start)
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
            } )
    Text(text = "小明", modifier = Modifier.constrainAs(name) {
start.linkTo(head.end)
        top.linkTo(head.top)
    } )
    Text(text = "13053136666", modifier = Modifier.constrainAs(phone) {
bottom.linkTo(head.bottom)
        start.linkTo(head.end)
    } )
} 

第二种解耦写法

ConstraintLayout(constraintSet = userInfoConstraints () ) {

 Icon(
        imageVector = Icons.Default.Person,
        contentDescription = null,
        modifier = Modifier
            .size(50.dp)
            .layoutId("head")
    )
    Text(text = "小明", modifier = Modifier.layoutId("name"))
    Text(text = "13053136666", modifier = Modifier.layoutId("phone"))
} 
private fun userInfoConstraints(): ConstraintSet {
    return ConstraintSet {
val head = createRefFor("head")
        val name = createRefFor("name")
        val phone = createRefFor("phone")

        constrain(head) {
start.linkTo(parent.start)
            top.linkTo(parent.top)
            bottom.linkTo(parent.bottom)
        }

constrain(name) {
start.linkTo(head.end)
            top.linkTo(head.top)
        }

constrain(phone) {
bottom.linkTo(head.bottom)
            start.linkTo(head.end)
        }
}
}

实现的效果和第一种是一样的。