系统提供的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;
})
}