Compose基础布局
常规布局
Compose 可以有效地处理嵌套布局,堪称设计复杂界面的绝佳工具。这与 Android Views 相比是一个进步;在 Android Views 中,出于性能方面的原因,需要避免使用嵌套布局。
Column示例:
@Composable
fun ArtistCard() {
Column {
Text("Alfred Sisley")
Text("3 minutes ago")
}
}
Row示例:
@Composable
fun ArtistCard(artist: Artist) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(/*...*/)
Column {
Text(artist.name)
Text(artist.lastSeenOnline)
}
}
}
Box示例:
@Composable
fun ArtistAvatar(artist: Artist) {
Box {
Image(/*...*/)
Icon(/*...*/)
}
}
ConstraintLayout
Jetpack Compose中依然支持ConstraintLayout。ConstraintLayout 有助于根据可组合项的相对位置将它们放置在屏幕上,它是使用多个嵌套 Row、Column、Box 和自定义布局元素的替代方案。在实现对齐要求比较复杂的较大布局时,ConstraintLayout 很有用。
如需使用ConstraintLayout ,需在build.gradle中添加依赖项:
implementation "androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha07"
Compose 中的 ConstraintLayout 支持 DSL:
-
引用是使用 createRefs() 或 createRefFor() 创建的,ConstraintLayout
中的每个可组合项都需要有与之关联的引用。 -
约束条件是使用 constrainAs() 修饰符提供的,该修饰符将引用作为参数,可让您在主体
lambda 中指定其约束条件。 -
约束条件是使用 linkTo() 或其他有用的方法指定的。
-
parent 是一个现有的引用,可用于指定对
ConstraintLayout 可组合项本身的约束条件。
ConstraintLayout示例:
@Composable
fun ConstraintLayoutContent() {
// ConstraintLayout布局,宽度默认与内容同宽,此处指定为同父布局最大宽度
ConstraintLayout(Modifier.fillMaxWidth()) {
// Create references for the composables to constrain
val (button, text) = createRefs()
Button(
onClick = { /*Do something*/ },
// Assign reference "button" to the Button composable
// and constrain it to the top of the ConstraintLayout
modifier = Modifier.constrainAs(button) {
//使用linkTo作为控件位置约束条件
top.linkTo(parent.top, margin = 16.dp)
//水平居中
centerHorizontallyTo(parent)
}
) {
Text(text = "Button")
}
// Assign reference "text" to the Text composable
// and constrain it to the bottom of the Button composable
Text(text = "Text", Modifier.constrainAs(text) {
//使用linkTo作为控件位置约束条件
top.linkTo(button.bottom, margin = 16.dp)
// bottom.linkTo(parent.bottom, margin = 16.dp)
// Centers Text horizontally in the ConstraintLayout
centerHorizontallyTo(parent)
})
}
}
在上述 ConstraintLayout 示例中,约束条件是在应用它们的可组合项中使用修饰符以内嵌方式指定的。不过,在某些情况下,最好将约束条件与应用它们的布局解耦:
- 将 ConstraintSet 作为参数传递给 ConstraintLayout。
- 使用 layoutId 修饰符将在 ConstraintSet 中创建的引用分配给可组合项。
@Composable
fun DecoupledConstraintLayout() {
BoxWithConstraints {
val constraints = if (minWidth < 600.dp) {
decoupledConstraints(margin = 16.dp) // Portrait constraints
} else {
decoupledConstraints(margin = 32.dp) // Landscape constraints
}
ConstraintLayout(constraints) {
Button(
onClick = { /* Do something */ },
modifier = Modifier.layoutId("button") // 指定id
) {
Text("Button")
}
Text("Text", Modifier.layoutId("text")) // 指定id
}
}
}
private fun decoupledConstraints(margin: Dp): ConstraintSet {
return ConstraintSet {
val button = createRefFor("button")
val text = createRefFor("text")
constrain(button) {
top.linkTo(parent.top, margin = margin)
}
constrain(text) {
top.linkTo(button.bottom, margin)
}
}
}