一:开发环境
二:效果图
三:实现步骤
@Entry
@Component
struct TabsPage {
@State tabArray:string[] = ["首页","分类","应用","热点","我的"]
@State focusIndex: number = 0;
@State index: number = 0;
private controller: TabsController = new TabsController();
private listScroller: Scroller = new Scroller();
private barHeight: number = 0;
@Builder
tabBuilder(tabName: string, tabIndex: number) {
Row() {
Text(tabName)
.fontSize(14)
.fontColor(tabIndex === this.focusIndex ? "#638EEF": "#E6000000")
.id(tabIndex.toString())
}
.justifyContent(FlexAlign.Center)
.width(60)
.backgroundColor(tabIndex === this.focusIndex ? "#243b75ef" : "")
.borderRadius(5)
.height(30)
.margin({ left: 8})
.onClick(() => {
this.controller.changeIndex(tabIndex)
// this.listScroller.scrollToIndex(tabIndex, true, ScrollAlign.CENTER);
this.listScroller.scrollToIndex(tabIndex)
})
}
build() {
Column() {
Stack().height(30)
Row() {
List({ scroller: this.listScroller }) {
ForEach(this.tabArray,(item: string, index: number)=>{
this.tabBuilder(item, index)
},(item: string, index: number) => JSON.stringify(item) + index)
}
.width('100%')
.height('100%')
.listDirection(Axis.Horizontal)
.scrollBar(BarState.Off)
}
.width('95%')
.alignItems(VerticalAlign.Center)
.height(50)
.margin({ top: 8 })
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
ForEach(this.tabArray,
(item: string) => {
TabContent() {
Row() {
Text(item)
.height(300)
.fontSize(30)
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
.backgroundColor(Color.White)
}, (item: string, index: number) => JSON.stringify(item) + index)
}
.width("100%")
.barHeight(this.barHeight)
.animationDuration(300)
.onChange((targetIndex: number)=>{
this.focusIndex = targetIndex
this.listScroller.scrollToIndex(targetIndex)
})
// .onAnimationStart((index: number, targetIndex: number) => {//api 9以长
// console.log( 'index', index.toString());
// this.focusIndex = targetIndex;
// this.listScroller.scrollToIndex(targetIndex, true, ScrollAlign.CENTER);
// })
}
}
}