鸿蒙系列之一弹性布局(Flex)

275 阅读2分钟

1.Flex弹性布局可以更加方便的对容器中的子元素进行排列、对齐和分配剩余空间等

  • 行的Flex跟Row组件的表现几乎一致,单列的Flex则跟Column组件表现几乎一致。但Row与Column 都是单行单列的,Flex则可以突破了这个限制,当主轴上空间不足时,则向纵轴上去扩展显示。
  1. Flex接口: Flex(value?:{direction?:FlexDirection,wrap?:FlexWrap,justifyContent?:FlexAlign,alignItems?:ItemAlign,alignContent?:FlexAlign}) 标准Flex布局容器。 从APIversion9开始,该接口支持在ArkTS卡片中使用。

3.Flex参数

参数名参数类型必填默认值参数描述
directionFlexDirectionFlexDirection.Row子组件在Flex容器上排列的方向,即主轴的方向。
wrapFlexWrapFlexWrap.NoWrapFlex容器是单行/列还是多行/列排列。说明:在多行布局时,通过交叉轴方向,确认新行堆叠方向。
justifyContentFlexAlignFlexAlign.Start子组件在Flex容器主轴上的对齐格式。
alignItemsItemAlignItemAlign.Start子组件在Flex容器交叉轴上的对齐格式。
alignContentFlexAlignFlexAlign.Start交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。

4.Flex轴的基本概念

  • 主轴:Flex组件布局方向的轴线,子元素默认沿着主轴排列。主轴开始的位置称为主轴起始点,结束位置称为主轴结束点。
  • 交叉轴:垂直于主轴方向的轴线。交叉轴开始的位置称为交叉轴起始点,结束位置称为交叉轴结束点

5.Flex应用案例

  • 弹性布局在开发场景中用例特别多,比如页面头部导航栏的均匀分布、页面框架的搭建、多行多列数据的排列等等。
  1. Flexdirection参数控制布局方向
  • Flex布局中通过direction可以改变布局方向,在弹性布局中,容器的子元素可以按照任意方向排列。通过设置参数direction,可以决定主轴的方向,从而控制子组件的排列方向。

image.png

  • direction:FlexDirection.Row
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Column(){
     Flex({direction:FlexDirection.Row}){
       Row(){
         Text('1')
           .width('100%')
           .fontSize(20)
           .fontColor(Color.White)
           .textAlign(TextAlign.Center)
       }
         .width('30%')
         .height(50)
         .backgroundColor(Color.Red)
       Row(){
         Text('2')
           .width('100%')
           .fontSize(20)
           .fontColor(Color.White)
           .textAlign(TextAlign.Center)
       }
         .width('30%')
         .height(50)
         .backgroundColor(Color.Green)
       Row(){
         Text('3')
           .width('100%')
           .fontSize(20)
           .fontColor(Color.White)
           .textAlign(TextAlign.Center)
       }
         .width('30%')
         .height(50)
         .backgroundColor(Color.Blue)
     }
      .width('100%')
      .height(300)
      .backgroundColor(Color.Grey)

    }
    .width('100%')
    .height('100%')

  }
}

image.png

  • direction:FlexDirection.RowReverse

image.png

  • direction:FlexDirection.Column

image.png

  • direction:FlexDirection.ColumnReverse

image.png