鸿蒙应用开发案例之Tabs组件-自定义TabBar底部导航

效果图:

鸿蒙应用开发案例之Tabs组件-自定义TabBar底部导航

实现代码:

Index.ets

@Entry
@Component
struct Index {
  @State currentIndex: number = 0;  // 设置当前选中的Index
  @State msgCount: number = 1;  // 消息数量
  @State cartCount: number = 2;  // 购物车数量

  @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')
        .fontSize(14)
      // 判断显示红点
      if(targetIndex === 2 || targetIndex === 3){
        Text(targetIndex === 2 ? this.msgCount+"" : this.cartCount+"")
          .id("textTab")
          .textAlign(TextAlign.Center)
          .backgroundColor(Color.Red)
          .borderRadius(10)
          .fontSize(12)
          .fontColor(Color.White)
          .width(20)
          .height(20)
          .alignRules({
            left: { anchor: 'textTab', align: HorizontalAlign.End },
            center: { anchor: 'textTab', align: VerticalAlign.Center }
          })
          .position({
            top:3,
            right:15
          })
      }
    }
    .width("100%")
    .height(50)
    .justifyContent(FlexAlign.Center)
  }

  build() {
    Column(){
      Tabs(){
        TabContent(){

        }
        .tabBar(this.tabBuilder('首页', 0, $rawfile("home_selected.png"), $rawfile("home_unselected.png")))

        TabContent(){

        }
        .tabBar(this.tabBuilder('视频', 1, $rawfile("video_selected.png"), $rawfile("video_unselected.png")))

        TabContent(){

        }
        .tabBar(this.tabBuilder('消息', 2, $rawfile("msg_selected.png"), $rawfile("msg_unselected.png")))

        TabContent(){

        }
        .tabBar(this.tabBuilder('购物车', 3, $rawfile("cart_selected.png"), $rawfile("cart_unselected.png")))

        TabContent(){

        }
        .tabBar(this.tabBuilder('我的', 4, $rawfile("my_selected.png"), $rawfile("my_unselected.png")))
      }
      .barPosition(BarPosition.End)   // 设置底部导航
      .barMode(BarMode.Fixed)  // 设置固定导航栏
      .scrollable(false)  // 设置不滚动
      .animationDuration(0)  // 设置动画执行时间
      .onChange((curIndex)=>{
        this.currentIndex = curIndex
      })
    }
    .width("100%")
    .height("100%")
  }
}

参考API:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-container-tabs#animationduration

 

原创文章,作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4809

(0)
czhdawn的头像czhdawn
上一篇 2025年7月8日 17:06
下一篇 2025年7月23日 21:10

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注