HarmonyOS/OpenHarmony应用开发-ArkTS自适应线性布局定位能力实现

1.相对定位,使用组件的offset属性可以实现相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。使用线性布局和offset可以实现大部分布局的开发。
代码实现

@Entry
@Component
struct OffsetExample {
  @Styles eleStyle() {
    .size({ width: 120, height: '50' })
    .backgroundColor(0xbbb2cb)
    .border({ width: 1 })
  }

  build() {
    Column({ space: 20 }) {
      Row() {
        Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
        Text('2  offset(15, 30)')
          .eleStyle()
          .fontSize(16)
          .align(Alignment.Start)
          .offset({ x: 15, y: 30 })
        Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
        Text('4 offset(-10%, 20%)')
          .eleStyle()
          .fontSize(16)
          .offset({ x: '-5%', y: '20%' })
      }.width('90%').height(150).border({ width: 1, style: BorderStyle.Dashed })
    }
    .width('100%')
    .margin({ top: 25 })
  }
} 


2.绝对定位
线性布局中可以使用组件的positon属性实现绝对布局(AbsoluteLayout),设置元素左上角相对于父容器左上角偏移位置。对于不同尺寸的设备,使用绝对定位的适应性会比较差,在屏幕的适配上有缺陷。
代码实现

 

@Entry
@Component
struct PositionExample {
  @Styles eleStyle(){
    .backgroundColor(0xbbb2cb)
    .border({ width: 1 })
    .size({ width: 120, height: 50 })
  }

  build() {
    Column({ space: 20 }) {
      // 设置子组件左上角相对于父组件左上角的偏移位置
      Row() {
        Text('position(30, 10)')
          .eleStyle()
          .fontSize(16)
          .position({ x: 10, y: 10 })

        Text('position(50%, 70%)')
          .eleStyle()
          .fontSize(16)
          .position({ x: '50%', y: '70%' })

        Text('position(10%, 90%)')
          .eleStyle()
          .fontSize(16)
          .position({ x: '10%', y: '80%' })
      }.width('90%').height('100%').border({ width: 1, style: BorderStyle.Dashed })
    }
    .width('90%').margin(25)
  }
}

效果展示


参考引用自官方文档。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值