HarmonyOS Next 底部 Tab 栏组件开发实战

2025-06-18 14:38:11
109次阅读
0个评论

底部 Tab 导航是移动应用中最常见的交互设计之一,HarmonyOS Next 提供了灵活高效的 Tabs 组件帮助开发者快速实现该功能。本文将通过完整示例讲解如何实现一个高度定制的底部 Tab 栏。

开发步骤详解

步骤 1:创建基础页面结构

@Entry
@Component
struct MainPage {
  @State currentIndex: number = 0 // 当前选中索引

  build() {
    Column() {
      // 内容区域
      this.ContentBuilder()

      // 底部Tab栏
      this.BottomTabs()
    }
    .height('100%')
  }
}

步骤 2:配置 Tab 页面内容

// 内容区域构建器
ContentBuilder() {
  if (this.currentIndex === 0) {
    HomePage()
  } else if (this.currentIndex === 1) {
    DiscoverPage()
  } else {
    MinePage()
  }
}

步骤 3:实现自定义 Tab 栏

// 底部导航构建器
@Builder
BottomTabs() {
  Flex({ justifyContent: FlexAlign.SpaceAround }) {
    this.TabItemBuilder(0, $r('app.media.home'), '首页')
    this.TabItemBuilder(1, $r('app.media.compass'), '发现')
    this.TabItemBuilder(2, $r('app.media.user'), '我的')
  }
  .width('100%')
  .height(60)
  .backgroundColor(Color.White)
  .shadow({ radius: 8, color: '#00000020', offsetX: 0, offsetY: -2 })
}

// 单个Tab项构建器
@Builder
TabItemBuilder(index: number, icon: Resource, text: string) {
  Column() {
    Image(icon)
      .width(24)
      .height(24)
      .objectFit(ImageFit.Contain)
      .fillColor(this.currentIndex === index ? '#FF1949' : '#999')

    Text(text)
      .fontSize(12)
      .fontColor(this.currentIndex === index ? '#FF1949' : '#999')
  }
  .onClick(() => {
    this.currentIndex = index
    // 可添加点击动画
    animateTo({ duration: 100 }, () => {})
  })
}
收藏00

登录 后评论。没有帐号? 注册 一个。

爱学习的小星星

  • 0回答
  • 0粉丝
  • 1关注
相关话题