HarmonyOS中实现TabBar(相当于Android中的TabLayout+ViewPager)

参考网址:自定义页签切换联动

1.自定义组件TabBarView

TypeScript 复制代码
@Component
export struct TabBarView{
  @State currentIndex: number = 0
  @State selectedIndex: number = 0
  private controller: TabsController = new TabsController()

  //tab标签内容+横线布局
  @Builder tabBuilder(index: number, name: string) {
    Column() {
      Text(name)
        .fontColor(this.selectedIndex === index ? '#007DFF' : '#182431')
        .fontSize(18)
        .fontWeight(this.selectedIndex === index ? 500 : 400)
        .lineHeight(22)
        .height('95%')
      Divider()
        .strokeWidth(2)
        .color('#007DFF')
        .opacity(this.selectedIndex === index ? 1 : 0)
    }
    .backgroundColor(Color.White)
    .width('100%')
    .height('100%')
  }

  @Link arr: Array<string>
  @Builder tabItem(item: string) {}
  @BuilderParam item: (item: string) => void = this.tabItem

  build() {
    Column() {
      Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
        ForEach(this.arr, (item: string, index: number) => {
          TabContent() {
            this.item(item)
          }.tabBar(this.tabBuilder(index, item))
        }, (item: string, index: number) => index.toString())
      }
      .vertical(false)
      .barMode(BarMode.Fixed)
      .barWidth(360)
      .barHeight(56)
      .animationDuration(400)
      .onChange((index: number) => {
        // currentIndex控制TabContent显示页签
        this.currentIndex = index
        this.selectedIndex = index
      })
      .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
        if (index === targetIndex) {
          return
        }
        // selectedIndex控制自定义TabBar内Image和Text颜色切换
        this.selectedIndex = targetIndex
      })
      .width('100%')
      .height('100%')
      .backgroundColor('#F1F3F5')
    }.width('100%')
  }
}

2.组件中使用

TypeScript 复制代码
import { TabBarView } from "./TabBarView"
@Entry({routeName: 'IndexPage'})

@Component
export struct IndexPage{

  @State arr: Array<string> = ['标签1', '标签2']
  @Builder
  tabItem(item: string){
    //在此处写各个标签对于的布局组件,可抽离出来使代码简洁
    if (item === this.arr[0]){
      //标签1组件
    }else if (item === this.arr[1]){
      //标签2组件
    }
  }
  build() {
    Column(){
      TabBarView({arr: this.arr, item: this.tabItem})
    }
  }
}

说明:我是根据官网提供的Tabs实例代码1(自定义页签切换联动) 封装的简单使用(代码可直接使用),这种方式是为了复用。

相关推荐
高心星4 小时前
HarmonyOS 5.0应用开发——MVVM模式的应用
harmonyos·mvvm·鸿蒙5.0·备忘录应用
别说我什么都不会5 小时前
【仓颉三方库】工具类—— compress4cj
harmonyos
别说我什么都不会5 小时前
【仓颉三方库】工具类—— uuid4cj
harmonyos
__Benco11 小时前
OpenHarmony - 小型系统内核(LiteOS-A)(十),魔法键使用方法,用户态异常信息说明
人工智能·harmonyos
NapleC1 天前
HarmonyOS:一多能力介绍:一次开发,多端部署
华为·harmonyos
我爱学习_zwj1 天前
【鸿蒙HarmonyOS】深入理解router与Navigation
华为·harmonyos
NapleC1 天前
HarmonyOS:1.7
harmonyos
鸿蒙布道师1 天前
鸿蒙NEXT开发通知工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
鸿蒙布道师1 天前
鸿蒙NEXT开发网络相关工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei