传统的View中使用的线性布局是 LinearLayout,Compose根据纵向和横向的方向不同分为 Column 和 Row 两种组件
Column 是一个垂直线性布局组件,可将子组件按顺序从上到下垂直排列
@Composable
inline fun Column(
modifier: Modifier = Modifier, //修饰符
verticalArrangement: Arrangement.Vertical = Arrangement.Top, //垂直位置
horizontalAlignment: Alignment.Horizontal = Alignment.Start, //水平位置
content: @Composable ColumnScope.() -> Unit //垂直作用域
)
注:Column 默认 垂直位置靠上,水平位置靠左
Column{
Text(text = "Hello,World",
style = MaterialTheme.typography.titleMedium)
Text(text = "Jetpack Compose")
}
Column(modifier = Modifier
.border(1.dp, Color.Red)){
Text(text = "Hello,World",
style = MaterialTheme.typography.titleMedium)
Text(text = "Jetpack Compose")
}
注:
加了边框后可以看出来,内容是包裹起来的
Column默认是没有指定宽高的,也就无法定位 Column 中的 子组件的位置定位 ,也就是无法使用 verticalArrangement,horizontalAlignment 定位 子组件位置
如果宽度和高度都指定了,就可以使用 verticalArrangement,horizontalAlignment 定位 子组件位置
Column(modifier = Modifier
.border(1.dp, Color.Red)
.size(200.dp),
verticalArrangement = Arrangement.Center){
Text(text = "Hello,World",
style = MaterialTheme.typography.titleMedium)
Text(text = "Jetpack Compose")
}
注:Arrangement.Center 为居中
Column(modifier = Modifier
.border(1.dp, Color.Red)
.size(200.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = "Hello,World",
style = MaterialTheme.typography.titleMedium)
Text(text = "Jetpack Compose")
}
注:Alignment.CenterHorizontally 为水平居中
Column(modifier = Modifier
.border(1.dp, Color.Red)
.size(200.dp),
verticalArrangement = Arrangement.Center
){
Text(text = "Hello,World",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.align(Alignment.CenterHorizontally))
Text(text = "Jetpack Compose")
}
注:modifier = Modifier.align(Alignment.CenterHorizontally)) 设置子组件 水平居中,Modifier.align 修饰符优先于 Column 的 horizontalAlignment 参数
Row组件是水平线性布局组件,可将子组件按顺序从左往右 水平排列
@Composable
inline fun Row(
modifier: Modifier = Modifier, //修饰符
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, //水平位置
verticalAlignment: Alignment.Vertical = Alignment.Top, //垂直位置
content: @Composable RowScope.() -> Unit //水平作用域
)
Row(modifier = Modifier
.fillMaxWidth()
.padding(top = 30.dp),
horizontalArrangement = Arrangement.SpaceAround) {
IconButton(onClick = { }) {
Icon(imageVector = Icons.Filled.Favorite, contentDescription = null)
}
IconButton(onClick = { }) {
Icon(imageVector = Icons.Filled.ShoppingCart, contentDescription = null)
}
IconButton(onClick = { }) {
Icon(imageVector = Icons.Filled.MailOutline, contentDescription = null)
}
}
注:Arrangement.SpaceAround 内容 撑满Row的宽度,最左边和最右边的组件与Row的间距是 组件与组件之间的间距的一半