鸿蒙布局元素篇(四)-相对布局(RelativeContainer)

364 阅读2分钟

看到这个名字能想到前端的定位,类似其中的相对定位但是定义和用法区别很大。支持相对于布局元素或者排列靠前的子元素定位,不支持数值的方式。比层叠布局容器对齐方式灵活性更高。

子元素有以下特性

  • 有一个属性id:被当做相对定位元素的描点标识,布局元素的值默认是__container__
  • 同层叠布局一样,排列靠后的元素层级更高
  • 有一个属性alignRules:用来描述对齐方式。如果没有声明对齐方式会默认相对于RelativeContainer元素居左和居上对齐

定位方向有两个参数

参数描述
anchor指定定位的元素
align相对瞄点的对齐方式
@Entry
@Component
struct Index3 {
  build() {
    Row() {
      RelativeContainer() {
        Row()
          .width(100)
          .height(100)
          .backgroundColor(0xd2cab3)
          .alignRules({
            top: { anchor: '__container__', align: VerticalAlign.Top },  //以父容器为锚点,竖直方向顶头对齐
            middle: { anchor: '__container__', align: HorizontalAlign.Center }  //以父容器为锚点,水平方向居中对齐
          })
          .id('row1')  //设置锚点为row1

        Row() {
          Image($r('app.media.icon'))
        }
        .height(100).width(100)
        .alignRules({
          top: { anchor: 'row1', align: VerticalAlign.Bottom },  //以row1组件为锚点,竖直方向底端对齐
          left: { anchor: 'row1', align: HorizontalAlign.Start }  //以row1组件为锚点,水平方向开头对齐
        })
        .id('row2')  //设置锚点为row2

        Row()
          .width(100)
          .height(100)
          .backgroundColor(0xc1cbac)
          .alignRules({
            top: { anchor: 'row2', align: VerticalAlign.Top }
          })
          .id('row3')  //设置锚点为row3
        Row()
          .width(50)
          .height(100)
          .backgroundColor(0xd2cab3)
            // 没有设置对齐方式,默认相对父容器居左居上
          .alignRules({
          })
          .id('row4')  //设置锚点为row4
        Row()
          .width(100)
          .height(40)
          .backgroundColor(0xc1cbac)
            // 没有设置对齐方式,默认相对父容器居左居上
          .alignRules({
          })
          .id('row5')  //设置锚点为row5
      }
      .width(300).height(300)
      .border({ width: 2, color: '#6699FF' })
    }
    .height('100%').margin({ left: 30 }).alignItems(VerticalAlign.Top)
  }
}

不同方向的对齐都也可以选择不同的描点,对于复杂场景的使用灵活度很高。

image.png