前言
弹性布局(Flex
)是一种高效的容器布局方式,通过灵活控制子元素在主轴与交叉轴上的排列方式,适应不同屏幕尺寸和动态内容需求。
一、布局核心属性
-
主轴方向
- 通过
direction
定义主轴方向,可选FlexDirection.Row
(水平)或FlexDirection.Column
(垂直)1。 - 默认主轴为水平方向(类似
Row
容器),子元素沿水平轴排列1。
Flex({ direction: FlexDirection.Row }) { Text('元素1').flexGrow(1) Text('元素2').flexGrow(2) }
- 通过
-
对齐方式
- 主轴对齐:
justifyContent
支持Start
(起始端对齐)、End
(末端对齐)、Center
(居中)和SpaceBetween
(两端间隔均匀分布)等模式。 - 交叉轴对齐:
alignItems
控制子元素在交叉轴方向的对齐方式,如Center
(垂直居中)。
- 主轴对齐:
-
子元素属性
flexGrow
:定义子元素在主轴上的拉伸比例(按权重分配剩余空间)。flexShrink
:设置子元素收缩比例(当空间不足时生效)。flexBasis
:指定子元素在主轴上的基准尺寸(优先级高于宽高属性)。
二、代码实现
本示例之展示了比较简单的几种Flex布局实现,更详细的使用请参考对应的API。
Column() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
Text('水平1/4').flexGrow(1).backgroundColor('#F2F2F2').textAlign(TextAlign.Center)
Text('水平2/4').flexGrow(2).backgroundColor('#D4D4D4').textAlign(TextAlign.Center) // 权重为左侧的2倍
Text('水平1/4').flexGrow(1).backgroundColor('#F2F2F2').textAlign(TextAlign.Center)
}.border({ width:1, color:Color.Orange })
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
Text('垂直头部')
.flexShrink(0) // 禁止收缩
.height(100)
.width('50%')
.textAlign(TextAlign.Center)
.backgroundColor(Color.Gray)
Text('垂直内容')
.flexShrink(1)
.height(300)
.backgroundColor('#E6E6E6')
.width('50%')
.textAlign(TextAlign.Center)
Text('垂直底部')
.flexShrink(2) // 收缩优先级最高
.height(100)
.width('50%')
.textAlign(TextAlign.Center)
.backgroundColor(Color.Gray)
}
.height(400) // 总高度不足时触发收缩
.backgroundColor('#D4D4D4')
.width('100%')
.border({ width:1, color:Color.Blue })
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
.backgroundColor(Color.Pink)
.alignItems(HorizontalAlign.Start)