You can add a new selectedIndex to identify the selected tabBar, while the original currentIndex still controls the display of TabContent tabs. Then, by switching selectedIndex in the onAnimationStart event, you can achieve that the tabBar switches synchronously when the tab content switching animation occurs.
Note that selectedIndex and currentIndex cannot be the same. Otherwise, no animation will occur when the page is switched. When variables are shared, the status update in the onAnimationStart event immediately triggers TabContent re-rendering. As a result, the system skips the transition animation.
Refer to the code snippet below.
@Component
struct TabsDemo {
@State tabArray: Array<number> = [0, 1, 2, 3];
@State selectedIndex: number = 0;
@State currentIndex: number = 0;
@State selectedFontColor: Color = Color.Blue;
@State fontColor: Color = Color.Black;
private controller: TabsController = new TabsController();
@Builder
tabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontSize(16)
.lineHeight(22)
.fontWeight(this.selectedIndex === index ? 500 : 400)
.fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor)
Divider()
.strokeWidth(2)
.color('#007DEF')
.opacity(this.selectedIndex === index ? 1 : 0)
}
.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
ForEach(this.tabArray,(item: number, index:number) => {
// The system has its own tab.
TabContent() {
Text('Content of the Me tab' + item)
.fontSize(30)
}
.tabBar(this.tabBuilder(item, 'bar' + item))
})
}
.onChange((index: number) => {
// CurrentIndex Control TabContent Display Tab.
this.currentIndex = index;
})
.onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
if(index === targetIndex) {
return;
}
// SelectedIndex controls the color switching between Image and Text in the custom TabBar.
this.selectedIndex = targetIndex;
})
}
.width('100%')
}
}