本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、线性布局基础
鸿蒙的线性布局通过 Column(垂直排列) 和 Row(水平排列) 容器实现,子元素默认沿主轴方向依次排列。 主轴与交叉轴定义:
- Column:主轴为垂直方向,交叉轴为水平方向
- Row:主轴为水平方向,交叉轴为垂直方向
二、核心API与方法详解
1. 间距控制(space属性)
设置子元素在主轴方向的等间距,适用于Column和Row容器。
示例代码:
// Column容器垂直间距20vp
Column({ space: 20 }) {
Text('子元素1').height(50).backgroundColor(Color.Green)
Text('子元素2').height(50).backgroundColor(Color.Orange)
}.width('100%')
// Row容器水平间距35vp
Row({ space: 35 }) {
Text('子元素1').width('15%').height(50)
Text('子元素2').width('15%').height(50)
}.width('90%')
效果:子元素在主轴方向上均匀分布
2. 主轴对齐(justifyContent)
控制子元素在主轴方向的对齐方式,参数为 FlexAlign 枚举:
- Start:首端对齐
- Center:居中对齐
- End:尾部对齐
- SpaceBetween:两端对齐,中间等距
- SpaceAround:子元素两侧等距(边缘间距为中间一半)
- SpaceEvenly:所有间距完全相等
示例:
Row() {
Text('子元素1').width(80).height(40)
Text('子元素2').width(80).height(40)
}
.justifyContent(FlexAlign.SpaceBetween) // 两端对齐
.width('100%').backgroundColor('#ccc')
适用场景:导航栏布局、按钮组排列
3. 交叉轴对齐(alignItems)
控制子元素在交叉轴方向的对齐方式,参数根据容器类型不同:
- Column容器:使用 HorizontalAlign(水平方向对齐)
- Start(左对齐)、Center(居中)、End(右对齐)
- Row容器:使用 VerticalAlign(垂直方向对齐)
- Top(顶部对齐)、Center(居中)、Bottom(底部对齐)
示例:
// Column容器内水平居中对齐
Column() {
Text('子元素').width('80%').height(50)
}.alignItems(HorizontalAlign.Center)
// Row容器内垂直底部对齐
Row() {
Text('子元素').width(80).height(40)
}.alignItems(VerticalAlign.Bottom)
效果:子元素在交叉轴上按指定方式对齐
4. 自适应布局技巧
- Blank组件:填充主轴剩余空间
Row() { Text('左侧内容') Blank() // 自动填充剩余空间 Text('右侧按钮') }
- layoutWeight属性:按权重分配剩余空间
规则:权重值越大,占据剩余空间的比例越高Column() { Text('权重1').layoutWeight(1).backgroundColor(Color.Pink) Text('权重2').layoutWeight(2).backgroundColor(Color.Orange) }
三、高级用法
1. 子元素独立对齐(alignSelf)
覆盖父容器的alignItems
设置,单独控制某个子元素的交叉轴对齐方式:
Column() {
Text('默认对齐')
Text('自定义对齐').alignSelf(HorizontalAlign.End)
}
.alignItems(HorizontalAlign.Start)
2. 复杂嵌套布局
通过Column和Row的嵌套实现网格效果:
Column() {
Row({ space: 10 }) {
Text('单元格1').layoutWeight(1)
Text('单元格2').layoutWeight(1)
}
Row({ space: 10 }) {
Text('单元格3').layoutWeight(1)
Text('单元格4').layoutWeight(1)
}
}
四、完整代码示例
@Entry
@Component
struct LinearLayoutExample {
build() {
Column({ space: 20 }) {
// 水平布局示例
Row({ space: 20 }) {
Text('按钮1').width('20%').height(50).backgroundColor(Color.Red)
Text('按钮2').width('20%').height(50).backgroundColor(Color.Blue)
}
.justifyContent(FlexAlign.SpaceEvenly)
.alignItems(VerticalAlign.Center)
// 垂直布局示例
Column() {
Text('内容块1').width('80%').height(60).backgroundColor('#F5DEB3')
Text('内容块2').width('80%').height(60).backgroundColor('#D2B48C')
}
.alignItems(HorizontalAlign.Center)
}
.width('100%').padding(20)
}
}
五、注意事项
- 性能优化:避免过度嵌套,复杂布局建议结合网格布局(Grid)或弹性布局(Flex) 。
- 响应式适配:使用百分比(如
'80%'
)或vp
单位实现多设备适配 。 - 调试技巧:通过背景色(
.backgroundColor()
)可视化布局边界