HarmonyOS 怎么修改tabbar的默认选中界面?

如题:HarmonyOS 怎么修改tabbar的默认选中界面?

阅读 580
1 个回答

请参考此demo:

@Entry
@Component
struct TabsExample {
  @State currentIndex: number = 2;
  private tabsController: TabsController = new TabsController();

  @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 ? '#1698CE' : '#6B6B6B')
    }
    .width('30%')
    .height(50)
    .justifyContent(FlexAlign.Center)
    .onClick(() => {
      this.currentIndex = targetIndex;
      this.tabsController.changeIndex(this.currentIndex);
    })
  }

  build() {
    Tabs({ barPosition: BarPosition.End, controller: this.tabsController }) {
      TabContent() {
        Column().width('100%').height('100%').backgroundColor('#00CB87')
      }
      .tabBar(this.TabBuilder('页签1', 0, $r('app.media.startIcon'), $r('app.media.startIcon')))

      TabContent() {
        Column().width('100%').height('100%').backgroundColor('#007DFF')
      }
      .tabBar(this.TabBuilder('页签2', 1, $r('app.media.icon'), $r('app.media.icon')))
      TabContent() {
        Column().width('100%').height('100%').backgroundColor('#F04B3D')
      }
      .tabBar(this.TabBuilder('页签3', 2, $r('app.media.icon'), $r('app.media.icon')))
      TabContent() {
        Column().width('100%').height('100%').backgroundColor('#F04B3D')
      }
      .tabBar(this.TabBuilder('页签4', 3, $r('app.media.icon'), $r('app.media.icon')))
      TabContent() {
        Column().width('100%').height('100%').backgroundColor('#FF6C3F')
      }
      .tabBar(this.TabBuilder('页签5', 4, $r('app.media.icon'), $r('app.media.icon')))
    }
    .barWidth('100%')
    .barHeight(50)
    .barMode(BarMode.Scrollable)
    .scrollable(true)
    .backgroundColor('#f2f3f5')
    .onChange((index: number) => {
      this.currentIndex = index;
    })
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进