鸿蒙布局元素篇(二)-弹性布局(Flex)

471 阅读3分钟

Flex布局元素有些功能和线性布局Row容器/Column容器是重合或者说包含他们的功能,适合更复杂的一些场景。

Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign }):和前端的flex布局定义基本一致。只用法传承参的方式,不是属性的方式。

参数参数类型描述
directionFlexDirectionRow(默认)/RowReverse/Column/ColumnReverse主轴的方向。
wrapFlexWrapNoWrap(默认)/Wrap/WrapReverse是否允许换行,WrapReverse反向排列并允许换行
justifyContentFlexAlignStart(默认)/Center/End/SpaceBetween/SpaceAround/SpaceEvenly主轴上的对齐格式。
alignItemsItemAlignAuto/Start(默认)/Center/End/Stretch/Baseline交叉轴上的对齐格式。
alignContentFlexWrapStart(默认)/Center/End/SpaceBetween/SpaceAround/SpaceEvenly交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。

direction

  • 值为Row或RowReverse, 理解为线性布局中的Row和反向Row,后面说的主轴就是水平方向,交叉轴就是垂直方向。
  • 值为Column或ColumnReverse,理解为线性布局中的Column和反向Column,后面说的主轴就是垂直方向,交叉轴就是水平方向。

和线性布局相同的内容就不列举了,以下列举一些换行相关已经Flex特别的一些参数

@Entry
@Component
struct Index4 {
  @Provide  message: string = 'Hello World'

  build() {
    Column({space: 10}){
      // 设定水平是主轴方向;反向排列并允许换行;在交叉轴元素之间的距离相同且与两边距离相同
      Flex({ direction: FlexDirection.Row,wrap: FlexWrap.WrapReverse,
        alignContent: FlexAlign.SpaceEvenly}) {
        Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
        Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('4').width('20%').height(50).backgroundColor(0xD2B48C)
        Text('5').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('6').width('20%').height(50).backgroundColor(0xD2B48C)
        Text('7').width('20%').height(50).backgroundColor(0xF5DEB3)
      }
      .height(200)
      .padding(10)
      .backgroundColor(0xAFEEEE)

      // 设定水平是纵向方向;允许换行;在交叉轴两边对齐且两元素之间的距离相同。
      Flex({ direction: FlexDirection.Column,wrap: FlexWrap.Wrap,
        alignContent: FlexAlign.SpaceBetween
      }) {
        Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
        Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('4').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('5').width('20%').height(50).backgroundColor(0xF5DEB3)
      }
      .width("100%")
      .height(200)
      .padding(10)
      .backgroundColor(0xAFEEEE)
      // 设定纵向是主轴方向;Stretch让子元素在交叉轴铺满;交叉轴元素之间的距离相同,到两边的距离是元素之间距离的一半
      Flex({ direction: FlexDirection.Column,alignItems: ItemAlign.Stretch,
        justifyContent: FlexAlign.SpaceAround
      }) {
        Text('1').width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('2').width('20%').height(50).backgroundColor(0xD2B48C)
        Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
      }

      .height(200)
      .width('100%')
      .padding(10)
      .backgroundColor(0xAFEEEE)
    }
  }
}

image.png

总结

属于是扩展版的线性布局,允许换行,以及扩充了交叉轴多行的对齐管理。