【HarmonyOS】掌握布局组件,提升应用体验

从今天开始,博主将开设一门新的专栏用来讲解市面上比较热门的技术 "鸿蒙开发",对于刚接触这项技术的小伙伴在学习鸿蒙开发之前,有必要先了解一下鸿蒙,从你的角度来讲,你认为什么是鸿蒙呢?它出现的意义又是什么?鸿蒙仅仅是一个手机操作系统吗?它的出现能够和Android和IOS三分天下吗?它未来的潜力能否制霸整个手机市场呢?

抱着这样的疑问和对鸿蒙开发的好奇,让我们开始今天对布局组件的掌握吧!

目录

布局组件

Column与Row组件(排列布局)

Stack组件(层叠布局)

Flex组件(弹性布局)

RelativeContainer组件(相对布局)

List组件(创建列表)

Grid组件(创建网格)


布局组件

在 ArkTS 中,布局组件是一种用于管理和布置其他组件的特殊组件。它们用于定义用户界面的结构和排列方式。以下是ArkTS的通用属性:

名称 参数说明 描述
width Length 设置组件自身的宽度
height Length 设置组件自身的高度
size Length 设置高宽尺寸
padding Padding | Length 设置内边距属性
margin Margin | Length 设置外边距属性
constraintSize Length 设置约束尺寸,组件布局时进行尺寸范围限制

Column与Row组件(排列布局)

Column与Row是鸿蒙开发中最最常用的布局组件,它们分别用于垂直和水平方向上的排列和布局子组件,下面是该两个组件的使用区别:

Column(列)

Column 组件将子组件在垂直方向上依次排列。子组件按照从上到下的顺序布局,每个子组件占据一行。Column 组件会根据子组件的大小自动调整自身的高度以适应内容。

Row(行)

Row 组件将子组件在水平方向上依次排列。子组件按照从左到右的顺序布局,每个子组件占据一列。Row 组件会根据子组件的大小自动调整自身的宽度以适应内容。

因此,Column 和 Row 的主要区别在于排列方向和布局方式。如果你想要在垂直方向上依次排列子组件,可以使用 Column 组件;如果你想要在水平方向上依次排列子组件,可以使用 Row 组件。以下是使用Column和Row的基本用法:

TypeScript 复制代码
@Entry
@Component
struct TEST {
  build() {
    Column({ space: 10 }){
      Row({ space: 10 }){
        Row(){
        }
        .width('33%')
        .height(160)
        .backgroundColor('red')
        .layoutWeight(1)
        Row(){
        }
        .width('33%')
        .height(160)
        .backgroundColor('green')
        .layoutWeight(1)
        Row(){
        }
        .width(100)
        .height(160)
        .backgroundColor('blue')
      }
      .width('100%')
      .height(160)

      Column({ space: 10 }){
        Row().width('100%').backgroundColor(Color.Gray).layoutWeight(1)
        Row().width('100%').backgroundColor(Color.Red).layoutWeight(2)
      }
      .width('100%')
      .height(160)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

呈现的结果如下:

Stack组件(层叠布局)

层叠布局(StackLayout)用于在屏幕上预留一块区域来显示组件中的元素,提供元素可以重叠的布局。层叠布局通过Stack容器组件实现位置的固定定位与层叠,容器中的子元素(子组件)依次入栈,后一个子元素覆盖前一个子元素,子元素可以叠加,也可以设置位置。

层叠布局具有较强的页面层叠、位置定位能力,其使用场景有广告、卡片层叠效果等。如下:

Stack组件通过alignContent参数实现位置的相对移动。如下表所示,支持九种对齐方式:

名称 描述
TopStart 顶部起始端。
Top 顶部横向居中。
TopEnd 顶部尾端。
Start 起始端纵向居中。
Center 横向和纵向居中。
End 尾端纵向居中。
BottomStart 底部起始端。
Bottom 底部横向居中。
BottomEnd 底部尾端。

以下是借助Stack组件进行的案例,代码如下:

javascript 复制代码
@Entry
@Component
struct TEST {
  @State list: number[] = [1, 2, 3]
  build() {
    Column(){
      Stack({ alignContent: Alignment.BottomEnd }){
        Stack({ alignContent: Alignment.TopStart}){
          Column(){
            List({ space: 10 }){
              ForEach(this.list,(item)=>{
                ListItem(){
                  Text(`${item}`)
                    .fontSize(30)
                    .width('100%')
                    .backgroundColor('#eee').height(50).textAlign(TextAlign.Center)
                }
              })
            }
            .margin({ bottom: 70 })
          }
          .margin({ top: 60 })
          .height('100%')
          Row(){
            Text('HarmonyOS')
              .fontSize(30)
              .fontColor(Color.White)
              .width('100%')
              .textAlign(TextAlign.Center)
          }
          .width('100%')
          .backgroundColor(Color.Orange)
          .height(50)
        }
        Button(){
          Text('+').fontSize(40).fontColor(Color.White)
        }
        .width(80)
        .height(80)
        .onClick( ()=> {
          this.list.push(this.list[this.list.length - 1] + 1)
        })
        .margin({ right: 10, bottom: 10 })
      }
    }
    .width('100%')
    .height('100%')
  }
}

最终呈现的结果如下:

Flex组件(弹性布局)

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

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

以下是flex常见的使用参数:

参数名 参数类型 必填 默认值 参数描述
direction FlexDirection FlexDirection.Row 主轴方向
wrap FlexWrap FlexWrap.NoWrap 确认容器是单行/列还是多行
justifyContent FlexAlign FlexAlign.Start 子组件在flex容器主轴上对齐格式
alignItems ItemAlign ItemAlign.Start 子组件在flex容器交叉轴上对齐格式
alignContent FlexAlign FlexAlign.Start 多行内容的对齐格式。wrap多行下生效

以下是通过 FlexDirection 来更改方向的操作:

javascript 复制代码
@Entry
@Component
struct TEST {
  build() {
    Column({ space: 20 }){
      // 主轴为水平方向,子组件从起始端沿着水平方向开始排布。
      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. 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)

      // 主轴为垂直方向,子组件从起始端沿着垂直方向开始排布。
      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. 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)
    }
    .width('100%')
    .height('100%')
  }
}

最终呈现的结果如下:

当然弹性布局方面还有许多其他的操作,这里就不再赘述了,详情请参考 文档

RelativeContainer组件(相对布局)

相对布局组件用于复杂场景中元素对齐的布局,支持容器内的子元素设置相对位置关系,子元素支持指定兄弟元素作为锚点,也支持指定父容器作为锚点,基于锚点做相对位置布局,下图表示相对布局的概念图,虚线表示位置的依赖关系:

通过以下的案例代码来学习相对布局的形成:

javascript 复制代码
@Entry
@Component
struct TEST {
  build() {
    Column(){
      // RelativeContainer必须包含子元素
      // RelativeContainer固定的id就是 __container__
      RelativeContainer(){
        // RelativeContainer里面的子元素必须配置id属性
        Text("1")
          .width(100)
          .height(100)
          .fontSize(30)
          .alignRules({ // 当前容器的属性
            right: {
              anchor: "__container__", // 锚点,传入容器id
              align: HorizontalAlign.End // 相对于锚点位置的布局
             }
          })
          .backgroundColor(Color.Blue)
          .id('test1')

        Text("2")
          .width(100)
          .height(100)
          .fontSize(30)
          .alignRules({ // 当前容器的属性
            middle: {
              anchor: "__container__", // 锚点,传入容器id
              align: HorizontalAlign.Center // 相对于锚点位置的布局
            }
          })
          .backgroundColor(Color.Orange)
          .id('test2')

        Text("3")
          .width(100)
          .height(100)
          .fontSize(30)
          .alignRules({ // 当前容器的属性
            bottom: {
              anchor: "__container__", // 锚点,传入容器id
              align: VerticalAlign.Bottom // 相对于锚点位置的布局
            },
            right: {
              anchor: "__container__", // 锚点,传入容器id
              align: HorizontalAlign.End // 相对于锚点位置的布局
            }
          })
          .backgroundColor(Color.Red)
          .id('test3')

        // 相对于 2 进行布局,使其在2的正上方
        Text("4")
          .width(100)
          .height(100)
          .fontSize(30)
          .alignRules({ // 当前容器的属性
            bottom: {
              anchor: "test2", // 锚点,传入容器id
              align: VerticalAlign.Top // 相对于锚点位置的布局
            },
            left: {
              anchor: "test2", // 锚点,传入容器id
              align: HorizontalAlign.Start // 相对于锚点位置的布局
            }
          })
          .backgroundColor(Color.Green)
          .id('test4')
          .offset({ // 微调位置
            y: -20,
            x: 0
          })
      }
      .width(300)
      .height(300)
      .border({
        width: 1,
        color: Color.Red
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

最终呈现的结果如下:

List组件(创建列表)

列表是一种复杂的容器,当列表项达到一定数量,内容超过屏幕大小时,可以自动提供滚动功能。它适合用于呈现同类数据类型或数据类型集,例如图片和文本。在列表中显示数据集合是许多应用程序中的常见要求(如通讯录、音乐列表、购物清单等)。其主要使用的参数如下:

参数名 参数类型 必填 参数描述
space number | string 子组件主轴方向的间隔。
initialIndex number 设置当前List初次加载时视口起始位置显示的item的索引值。
scroller Scroller 可滚动组件的控制器。用于与可滚动组件进行绑定。

以下是使用List组件的案例:

javascript 复制代码
@Entry
@Component
struct TEST {
  list: number[] = [1, 2, 3, 4, 5, 6, 7]

  build() {
    Column(){
      List({ space: 20 }){
        ForEach(this.list,(item) => {
          ListItem(){
            Text(`${item}`)
              .textAlign(TextAlign.Center)
              .width('100%')
              .height(100)
              .fontSize(30)
          }
          .backgroundColor(0xffffff)
        })
      }
      .listDirection(Axis.Vertical) // 配置list显示方向
      .scrollBar(BarState.Auto) // 显示滚动条
      .padding(10)
      .divider({
        strokeWidth: 5,
        color: Color.Red,
        startMargin: 20,
        endMargin: 20
      })
    }
    .backgroundColor('#cccccc')
    .width('100%')
    .height('100%')
  }
}

最终呈现的效果如下:

Grid组件(创建网格)

网格布局是由"行"和"列"分割的单元格所组成,通过指定"项目"所在的单元格做出各种各样的布局。网格布局具有较强的页面均分能力,子组件占比控制能力,是一种重要自适应布局,其使用场景有九宫格图片展示、日历、计算器等。

名称 描述 名称 描述
columnsTemplate 设置当前网格布局列的数量 rowsTemplate 设置当前网格布局行的数量
columnsGap 设置列与列的间距。 rowsGap 设置行与行的间距。
scrollBar 设置滚动条状态。 scrollBarColor 设置滚动条的颜色。
scrollBarWidth 设置滚动条的宽度。 cachedCount 设置预加载的GridItem的数量,只在LazyForEach中生效。
editMode 设置Grid是否进入编辑模式 layoutDirection 设置布局的主轴方向。
minCount 示可显示的最小行/列数。 cellLength 表示一行的高度/一列的宽度
multiSelectable 是否开启鼠标框选。 supportAnimation 是否支持动画。

基础按钮如下:

javascript 复制代码
@Entry
@Component
struct TEST {
  build() {
    Column(){
      Grid(){
        GridItem(){
          Text("1")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        .rowStart(1)
        .rowEnd(2)
        GridItem(){
          Text("2")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        .columnStart(2)
        .columnEnd(3)
        GridItem(){
          Text("3")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        GridItem(){
          Text("4")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        GridItem(){
          Text("5")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        GridItem(){
          Text("6")
            .fontSize(16).fontColor(Color.White).backgroundColor('red')
            .width('100%').height('100%').textAlign(TextAlign.Center)
        }
        .columnStart(2)
        .columnEnd(3)
      }
      .columnsTemplate('1fr 1fr 1fr') // 显示3列
      .columnsGap(10)
      .rowsTemplate('1fr 2fr 1fr') // 显示3行 ,第二行宽度占总宽度二分之一
      .rowsGap(10)
      .height(300)
    }
  }
}

呈现的效果如下所示:

相关推荐
真正的能量来自内心26 分钟前
如何删除EXCELL文件中的空行?
经验分享
爱桥代码的程序媛35 分钟前
鸿蒙OpenHarmony【轻量系统芯片移植案例】标准系统方案之瑞芯微RK3568移植案例
嵌入式硬件·harmonyos·鸿蒙·鸿蒙系统·移植·openharmony·鸿蒙开发
AORO_BEIDOU1 小时前
防爆手机+鸿蒙系统,遨游通讯筑牢工业安全基石
5g·安全·智能手机·信息与通信·harmonyos
重生之我在20年代敲代码4 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
铁匠匠匠8 小时前
从零开始学数据结构系列之第六章《排序简介》
c语言·数据结构·经验分享·笔记·学习·开源·课程设计
天玑y11 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
逢生博客12 小时前
Mac 搭建仓颉语言开发环境(Cangjie SDK)
macos·华为·鸿蒙
青柠_项目管理13 小时前
PMP证书持有者,在华为、腾讯一般能拿多少薪资?
华为·pmp
小强在此16 小时前
【基于开源鸿蒙(OpenHarmony)的智慧农业综合应用系统】
华为·开源·团队开发·智慧农业·harmonyos·开源鸿蒙