HarmonyOS之自定义tab

系统提供的tab组件,在开发中不能满足需求。需要自定义一套适合自己项目的tab,这里给出大致思路,请根据具体需求更改。

首先,利用List组件的可滑动性,定制tab

关键代码:

// 当前位置
@Prop @Watch('changeIndex') currentIndex: number = 0;
// 点击回调
callBack?: (index: number) => void
// 监听外部内容滑动的位置,滑动tab到相应的位置
// ScrollAlign.AUTO 设置list在一屏的时候,滑动页面不跟随
changeIndex() {
      this.scroller.scrollToIndex(this.currentIndex,false,ScrollAlign.AUTO)
  }

build() {
    List({ scroller: this.scroller }) {
      ForEach(this.discoverTabList, (item: Model, index: number) => {
        ListItem() {
          Row() {
            Column() {
              Text(item.title)
                .fontSize(18)
                .fontColor('#212223')
                .fontWeight(600)
                .width(70)
                .height(18)
                .textAlign(TextAlign.Center)
              Stack({ alignContent: Alignment.Center }) {
                if (this.currentIndex == index) {
                  Row() {}
                  .margin({ top: 1 })
                  .padding({ left: this.currentIndex == index ? 7 : 0, right: this.currentIndex == index ? 7 : 0 })
                  .linearGradient({
                    colors: this.currentIndex == index ? [['#4F9BFF', 0.0], ['#80CAFF', 1.0]] : [],
                    direction: GradientDirection.Left
                  })
                  .borderRadius(17)
                  .justifyContent(FlexAlign.Center)
                  
                }

                Text(item.subTitle)
                  .fontSize(this.currentIndex == index ? 11 : 12)
                  .fontColor(this.currentIndex ==
                    index ? '#FFFFFF' : '#999999')
                  .fontWeight
                  (FontWeight.Regular)
                  .width(58)
                  .textAlign(TextAlign.Center)
                  .margin({ top: this.currentIndex == index ? 1 : 5 })
              }

            }.alignItems(HorizontalAlign.Center)

            Row().width(0.5).height(35).backgroundColor('#1A000000')
          }
        }.onClick(() => {
          this.currentIndex = index;
          this.scroller.scrollToIndex(this.currentIndex, false, ScrollAlign.AUTO)
          if (this.callBack) {
            this.callBack(item,index);
          }
        })
      },
        (item: TimeSceneDiscoverTabItemModel) => JSON.stringify(item))
    }
    .width('100%')
    .height(66)
    .scrollBar(BarState.Off)
    .listDirection(Axis.Horizontal)
    .padding({ left: 12, right: 12, top: 15 })
    .onScrollIndex((start, end) => {
      this.currentIndex == end;
    })

  }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值