ListItem() { Column() { Text((item == 2) ? '页签222222' : ('页签' + item)) .fontWeight(index === this.focusIndex ? FontWeight.Bold : FontWeight.Normal) .onAreaChange((newValue: Area) => { if (index === this.focusIndex) { this.sizeValue = newValue.width; } }); if (index === this.focusIndex) { Column().width(this.sizeValue).height(2).backgroundColor(Color.Gray); } }; } .borderRadius(10).backgroundColor(0xFFFFFF) .height(50) .onClick(() => { this.controller.changeIndex(index); this.focusIndex = index; this.scrollerForList.scrollToIndex(index, true, ScrollAlign.CENTER); });
Text((item == 2) ? '页签222222' : ('页签' + item)) .fontWeight(index === this.focusIndex ? FontWeight.Bold : FontWeight.Normal) .onAreaChange((newValue: Area) => { if (index === this.focusIndex) { this.sizeValue = newValue.width; } });
if (index === this.focusIndex) { Column().width(this.sizeValue).height(2).backgroundColor(Color.Gray); }
完整示例参考如下:
@Entry @Component struct TabsExample { @State tabArray: number[] = [0, 1, 2, 3, 4]; @State focusIndex: number = 0; private controller: TabsController = new TabsController(); private scrollerForList: Scroller = new Scroller(); @State sizeValue: Length = 0; build() { Column() { // 使用自定义页签组件 List({ space: 20, initialIndex: 0, scroller: this.scrollerForList }) { ForEach(this.tabArray, (index: number, item: number) => { ListItem() { Column() { Text((item == 2) ? '页签222222' : ('页签' + item)) .fontWeight(index === this.focusIndex ? FontWeight.Bold : FontWeight.Normal) .onAreaChange((newValue: Area) => { if (index === this.focusIndex) { this.sizeValue = newValue.width; } }); if (index === this.focusIndex) { Column().width(this.sizeValue).height(2).backgroundColor(Color.Gray); } }; } .borderRadius(10).backgroundColor(0xFFFFFF) .height(50) .onClick(() => { this.controller.changeIndex(index); this.focusIndex = index; this.scrollerForList.scrollToIndex(index, true, ScrollAlign.CENTER); }); }, (item: number) => JSON.stringify(item)); } .chainAnimation(true) .edgeEffect(EdgeEffect.Spring) .listDirection(Axis.Horizontal) .height('50') .width('100%') .scrollBar(0); Tabs({ barPosition: BarPosition.Start, controller: this.controller }) { ForEach(this.tabArray, (item: number) => { TabContent() { Text('我是页面 ' + item + ' 的内容') .fontSize(30); }; }); }.barHeight(0) .onChange((index: number) => { // currentIndex控制TabContent显示页签 this.focusIndex = index; this.scrollerForList.scrollToIndex(index, true, ScrollAlign.CENTER); }); } .height('100%') .width('100%'); } }