HarmonyOS Next应用开发实战——多页面切换的Tab页实现(part2)

103 阅读1分钟
3. 页面内容展示

使用TabsTabContent组件实现多页面切换,根据当前选中的Tab索引,显示对应的页面内容。

Tabs({
  barPosition: this.breakPoint === CommonConstants.BREAK_POINT_LG ? BarPosition.Start : BarPosition.End,
  index: this.currentTabIndex
}) {
  TabContent() {
    if (this.currentTabIndex === 0) {
      ExplorePage()
    }
  }
  .tabBar(this.BuildTabs($r('app.media.bottomtab_item'), '首页', 0))

  TabContent() {
    if (this.currentTabIndex === 1) {
      ShoppingMallPage()
    }
  }
  .tabBar(this.BuildTabs($r('app.media.cart'), '商城', 1))

  TabContent() {
    if (this.currentTabIndex === 2) {
      BuyingCarPage()
    }
  }
  .tabBar(this.BuildTabs($r('app.media.direction_car'), '选车', 2))

  TabContent() {
    if (this.currentTabIndex === 3) {
      ServicePage()
    }
  }
  .tabBar(this.BuildTabs($r('app.media.service'), '服务', 3))

  TabContent() {
    if (this.currentTabIndex === 4) {
      MinePage()
    }
  }
  .tabBar(this.BuildTabs($r('app.media.person'), '我的', 4))
}
.onChange((index: number) => {
  this.currentTabIndex = index;
})
4. 响应式布局

根据不同的屏幕尺寸断点,动态调整Tab栏的位置、宽度和高度。

GridRow({
  breakpoints: { value: CommonConstants.BREAK_POINTS_VALUE, reference: BreakpointsReference.WindowSize },
  columns: { sm: CommonConstants.COLUMN_SM, md: CommonConstants.COLUMN_MD, lg: CommonConstants.COLUMN_LG },
  direction: GridRowDirection.Row
}) {
  GridCol({
    span: { sm: CommonConstants.COLUMN_SM, md: CommonConstants.COLUMN_MD, lg: CommonConstants.COLUMN_LG }
  }) {
    Column() {
      Tabs({
        barPosition: this.breakPoint === CommonConstants.BREAK_POINT_LG ? BarPosition.Start : BarPosition.End,
        index: this.currentTabIndex
      })
      .vertical(this.breakPoint === CommonConstants.BREAK_POINT_LG)
      .barWidth(this.breakPoint === CommonConstants.BREAK_POINT_LG ? TabConstants.TAB_BAR_L_WIDTH :
      TabConstants.TAB_BAR_HEIGHT)
      .barHeight(this.breakPoint === CommonConstants.BREAK_POINT_LG ? TabConstants.TAB_BAR_L_HEIGHT :
      TabConstants.TAB_BAR_M_HEIGHT)
      .scrollable(false)
    }
  }
}
.onBreakpointChange((breakpoints: string) => {
  this.breakPoint = breakpoints;
})

通过以上核心功能的实现,开发者可以在HarmonyOS Next应用中创建一个功能完善的多页面切换Tab页。