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(自定义页签切换联动) 封装的简单使用(代码可直接使用),这种方式是为了复用。

相关推荐
二二孚日12 分钟前
自用华为ICT云赛道AI第三章知识点-昇腾芯片硬件架构,昇腾芯片软件架构
人工智能·华为
长弓三石1 小时前
鸿蒙网络编程系列57-仓颉版固定包头可变包体解决TCP粘包问题
网络·tcp/ip·harmonyos
zhanshuo2 小时前
HarmonyOS 隐私安全机制实战:动态权限、沙箱隔离与分布式授权
harmonyos
zhanshuo2 小时前
鸿蒙系统防黑秘籍:如何彻底防止恶意应用窃取用户数据?
harmonyos
财经三剑客5 小时前
鸿蒙智行6月交付新车52747辆 单日交付量3651辆
华为·harmonyos
睿麒6 小时前
鸿蒙app 开发中的 map 映射方式和用法
华为·harmonyos
呆呆的小鳄鱼7 小时前
牛客:HJ17 坐标移动[华为机考][字符串]
华为
zhanshuo8 小时前
鸿蒙 Secure Boot 全流程解析:从 BootROM 到内核签名验证的实战指南
harmonyos
zhanshuo8 小时前
鸿蒙系统安全机制全解:安全启动 + 沙箱 + 动态权限实战落地指南
harmonyos
塞尔维亚大汉8 小时前
鸿蒙内核源码分析(用户态锁篇) | 如何使用快锁Futex(上)
harmonyos·源码阅读