/**
* 不解耦api
*/
@Composable
fun DecoupledConstraintLayoutContent() {
val margin = 16.dp
ConstraintLayout {
//通过createRefs创建引用,
val (button, text) = createRefs()
Button(onClick = { },
modifier = Modifier.constrainAs(button) {
//使用linkTo制定约束 parent 是ConstraintLayout的引用
top.linkTo(parent.top, margin = margin)
start.linkTo(parent.start, margin = margin)
}) {
Text("Button")
}
Text("Text", modifier = Modifier.constrainAs(text) {
//使用linkTo制定约束 parent 是ConstraintLayout的引用
top.linkTo(button.bottom, margin = margin)
start.linkTo(parent.start, margin = margin)
//在协调者布局中居中
centerHorizontallyTo(parent)
})
}
}
正常情况下我们喜欢把约束写到一起。但是约束也可以抽取出来
/**
* 不解耦api
*/
@Composable
fun DecoupledConstraintLayoutContent2() {
BoxWithConstraints() {
val constraints = if (maxWidth < maxHeight) {
decoupledConstraintLayoutContent2(16.dp)
} else {
decoupledConstraintLayoutContent2(160.dp)
}
ConstraintLayout(constraints) {
//通过createRefs创建引用,
Button(
onClick = { },
modifier = Modifier.layoutId("button")
) {
Text("Button")
}
Text("Text", modifier = Modifier.layoutId("text"))
}
}
}
private fun decoupledConstraintLayoutContent2(margin: Dp): ConstraintSet {
return ConstraintSet {
val button = createRefFor("button")
val text = createRefFor("text")
constrain(button) {
top.linkTo(parent.top, margin)
start.linkTo(parent.start, margin = margin)
}
constrain(text) {
top.linkTo(button.bottom, margin)
start.linkTo(parent.start, margin = margin)
}
}
}
由于判断了宽高
val constraints = if (maxWidth < maxHeight) {
decoupledConstraintLayoutContent2(16.dp)
} else {
decoupledConstraintLayoutContent2(160.dp)
}
所以将会是不同的显示
竖屏
横屏