ArcTs布局入门02——弹性布局(Flex)

如果你对鸿蒙开发感兴趣,加入“Harmony自习室”吧~👇🏻👇🏻👇🏻👇🏻

扫描下面的二维码关注公众号。

1、概述

弹性布局(Flex)提供更加有效的方式对容器中的子元素进行排列、对齐和分配剩余空间。容器默认存在主轴与交叉轴,子元素默认沿主轴排列,子元素在主轴方向的尺寸称为主轴尺寸,在交叉轴方向的尺寸称为交叉轴尺寸。弹性布局在开发场景中用例特别多,比如页面头部导航栏的均匀分布、页面框架的搭建、多行数据的排列等等。

主轴为水平方向的Flex容器示意图

图片

2、基本概念

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

  • 交叉轴:垂直于主轴方向的轴线。交叉轴开始的位置称为交叉轴起始点,结束位置称为交叉轴结束点。

3、布局方向

在弹性布局中,容器的子元素可以按照任意方向排列。通过设置参数direction,可以决定主轴的方向,从而控制子组件的排列方向。

弹性布局方向图

图片

  • FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布

Flex({ direction: FlexDirection.Row }) {
  
    Text('1').width('33%').height(50).backgroundColor(0xF5DEB3)  Text('2').width('33%').height(50).backgroundColor(0xD2B48C)  Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)}.height(70).width('90%').padding(10).backgroundColor(0xAFEEEE)

图片

  • FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection. Row相反的方向开始排布

Flex({ direction: FlexDirection.RowReverse }) {
  
    Text('1').width('33%').height(50).backgroundColor(0xF5DEB3)  Text('2').width('33%').height(50).backgroundColor(0xD2B48C)  Text('3').width('33%').height(50).backgroundColor(0xF5DEB3)}.height(70).width('90%').padding(10).backgroundColor(0xAFEEEE)

图片

  • FlexDirection.Column:主轴为垂直方向,子组件从起始端沿着垂直方向开始排布

Flex({ direction: FlexDirection.Column }) {
  
    Text('1').width('100%').height(50).backgroundColor(0xF5DEB3)  Text('2').width('100%').height(50).backgroundColor(0xD2B48C)  Text('3').width('100%').height(50).backgroundColor(0xF5DEB3)}.height(70).width('90%').padding(10).backgroundColor(0xAFEEEE)

图片

  • FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection. Column相反的方向开始排布

Flex({ direction: FlexDirection.ColumnReverse }) {
  
    Text('1').width('100%').height(50).backgroundColor(0xF5DEB3)  Text('2').width('100%').height(50).backgroundColor(0xD2B48C)  Text('3').width('100%').height(50).backgroundColor(0xF5DEB3)}.height(70).width('90%').padding(10).backgroundColor(0xAFEEEE)

图片

4、布局换行

弹性布局分为单行布局和多行布局。默认情况下,Flex容器中的子元素都排在一条线(又称“轴线”)上。wrap参数控制当子元素主轴尺寸之和大于容器主轴尺寸时,Flex是单行布局还是多行布局。在多行布局时,通过交叉轴方向,确认新行堆叠方向。

  • FlexWrap. NoWrap(默认值):不换行。如果子组件的宽度总和大于父元素的宽度,则子组件会被压缩宽度

Flex({ wrap: FlexWrap.NoWrap }) {
  
    Text('1').width('50%').height(50).backgroundColor(0xF5DEB3)  Text('2').width('50%').height(50).backgroundColor(0xD2B48C)  Text('3').width('50%').height(50).backgroundColor(0xF5DEB3)} .width('90%').padding(10).backgroundColor(0xAFEEEE)

图片

  • FlexWrap. Wrap:换行,每一行子组件按照主轴方向排列

Flex({ wrap: FlexWrap.Wrap }) {
  
    Text('1').width('50%').heig
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值