#鸿蒙学习大百科#如何实现Tabs导航栏在手机端在底部,在平板端在左边显示?

如何实现Tabs导航栏在手机端在底部,在平板端在左边显示?

HarmonyOS
2024-09-26 09:54:53
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
朝花惜拾丶

(1)获取当前设备尺寸信息

windowStage.getMainWindow().then((data: window.Window) => {
  this.windowObj = data;
  this.updateBreakpoint(this.windowObj.getWindowProperties().windowRect.width,
    this.windowObj.getWindowProperties().windowRect.height);
  this.windowObj.on('windowSizeChange', (windowSize: window.Size) => {
    this.updateBreakpoint(windowSize.width, windowSize.height);
  })
})
private windowObj?: window.Window;
private updateBreakpoint(windowWidth: number, windowHeight: number): void {
  let windowWidthVp = windowWidth / display.getDefaultDisplaySync().densityPixels;
  let curBp: string = '';
  if (windowWidthVp < 600) {
    curBp = 'sm';
  } else if (windowWidthVp < 840) {
    curBp = 'md';
  } else {
    curBp = 'lg';
  }
  AppStorage.setOrCreate('breakPoint', curBp);
  AppStorage.setOrCreate('windowSize', windowWidth / display.getDefaultDisplaySync().densityPixels);
  AppStorage.setOrCreate('windowSizeHeight', windowHeight / display.getDefaultDisplaySync().densityPixels);
};
@Entry
@Component
struct Index {
  @StorageLink('breakPoint') breakPoint: string = '';
  @State currentIndex: number = 0
  controller: TabsController = new TabsController()
  @State titles: string[] = ["首页", "发现", "我的"]
  build() {
    Column() {
      Tabs({
        //设置导航位置
        barPosition: this.breakPoint === "lg" ? BarPosition.Start : BarPosition.End,
        controller: this.controller
      }) {
        ForEach(this.titles, (item: string, index: number) => {
          TabContent() {
            Text("je")
          }.tabBar(this.tabBuilder(item, index, $r("app.media.app_icon"), $r("app.media.app_icon")))
        })
      }
      .barHeight(this.breakPoint==="lg"?"100%":50)//根据具体情况设置导航栏的宽高
      .barWidth(this.breakPoint==="lg"?50:"100%")
      .barBackgroundColor(Color.White)
      .animationDuration(0)
      .vertical(this.breakPoint==="lg"?true:false)//设置方向
      .onChange((index: number) => {
        this.currentIndex = index
      })
      .onTabBarClick((index) => {
        this.currentIndex = index
      })

    }
    .height('100%')
    .width('100%')
  }

  @Builder
  tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
    Column() {
      Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
        .size({ width: 25, height: 25 })
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#007AFF' : '#6B6B6B')
    }
    .width('100%')
    .height(50)
    .justifyContent(FlexAlign.Center)
    .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  }
}
分享
微博
QQ
微信
回复
2024-09-26 16:14:20
相关问题