HarmonyOS应用开发——层叠布局

发布于:2025-06-24 ⋅ 阅读:(16) ⋅ 点赞:(0)

        在 HarmonyOS 应用开发的世界里,界面布局如同搭建高楼大厦的框架,决定着用户与应用交互的第一印象和使用体验。合理的布局不仅能让界面元素整齐有序、美观协调,还能适应不同设备的屏幕尺寸和分辨率。本文将深入剖析 HarmonyOS 中的常见布局方式,帮助开发者打造出出色的应用界面。

前置条件

        在开始本文章内容之前,博主希望开发者已完成 HarmonyOS 开发环境 的搭建。详情请参考:HarmonyOS 开发环境搭建

 层叠布局(StackLayout)

应用场景:

  • 组件需要有堆叠效果时优先考虑此布局。层叠布局的堆叠效果不会占用或影响其他同容器内子组件的布局空间。

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

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

let MTop:Record<string,number> = { 'top': 50 }


@Entry
@Component
struct StackExample {
  build() {
    Column(){
      Stack({ }) {
        Column(){}.width('90%').height('100%').backgroundColor('#ff58b87c')
        Text('text').width('60%').height('60%').backgroundColor('#ffc3f6aa')
        Button('button').width('30%').height('30%').backgroundColor('#ff8ff3eb').fontColor('#000')
      }.width('100%').height(150).margin(MTop)
    }
  }
}

 对齐方式

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

@Entry
@Component
struct StackExample {
  build() {
    // TopStart | Top | TopEnd | Start | Center | End | BottomStart | Bottom | BottomEnd
    Stack({ alignContent: Alignment.TopStart }) {
      Text('Stack').width('90%').height('100%').backgroundColor('#e1dede').align(Alignment.BottomEnd)
      Text('Item 1').width('70%').height('80%').backgroundColor(0xd2cab3).align(Alignment.BottomEnd)
      Text('Item 2').width('50%').height('60%').backgroundColor(0xc1cbac).align(Alignment.BottomEnd)
    }.width('100%').height(150).margin({ top: 5 })
  }
}

Z序控制

        Stack 容器中兄弟组件显示层级关系可以通过 Z序控制 的 zIndex属性 改变。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。 

@Entry
@Component
struct StackExample {
  build() {
    Stack({ alignContent: Alignment.BottomStart }) {
      Column() {
        Text('Stack子元素1').fontSize(20)
      }.width(100).height(100).backgroundColor(0xffd306).zIndex(2)

      Column() {
        Text('Stack子元素2').fontSize(20)
      }.width(150).height(150).backgroundColor(Color.Pink).zIndex(1)

      Column() {
        Text('Stack子元素3').fontSize(20)
      }.width(200).height(200).backgroundColor(Color.Grey)
    }.width(350).height(350).backgroundColor(0xe0e0e0)
  }
}

 


网站公告

今日签到

点亮在社区的每一天
去签到