点击Tab切换页签时,如何让Tab页签滚动到第二个位置


HarmonyOS NEXT
2025-07-21 14:33:38
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673c38b96e729
import { componentUtils, curves, display } from '@kit.ArkUI';

@Entry
@Component
struct ScrollSecondButton {
  @State indicatorIndex: number = 0
  @State displayInfo: display.Display | null = null
  private scroller: Scroller = new Scroller()
  private arr: string[] = ['全部内容', '体检', '老年体检', '中年体检', '视频', '老年体检', '新歌', '入职体检', '新片']

  aboutToAppear(): void {
    this.displayInfo = display.getDefaultDisplaySync(); //获取屏幕实例
  }

  // 获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
  private getTextInfo(index: number): Record<string, number> {
    let modePosition: componentUtils.ComponentInfo =
      this.getUIContext().getComponentUtils().getRectangleById(index.toString());
    try {
      return { 'left': px2vp(modePosition.windowOffset.x), 'width': px2vp(modePosition.size.width) }
    } catch (error) {
      return { 'left': 0, 'width': 0 }
    }
  }

  private scrollIntoView(currentIndex: number): void {
    const currentOffsetX: number = this.scroller.currentOffset().xOffset //当前滚动的偏移量

    // 获取currentIndex 前两个按钮宽度
    if (currentIndex >= 1) {
      const PreviousOne = this.getTextInfo(currentIndex - 1)
      // 将按钮滚动到第二个按钮
      this.scroller.scrollTo({
        xOffset: currentOffsetX + PreviousOne.left,
        yOffset: 0,
        animation: {
          duration: 300,
          curve: curves.interpolatingSpring(7, 1, 328, 34)   // 动画曲线
        }
      })
    } else {
      this.scroller.scrollTo({
        xOffset: 0,
        yOffset: 0
      })
    }

  }

  build() {
    Column() {
      Scroll(this.scroller) {
        Row() {
          ForEach(this.arr, (item: string, index: number) => {
            Column() {
              Text(item)
                .fontSize(16)
                .borderRadius(5)
                .fontColor(this.indicatorIndex === index ? "#3ca4dc" : Color.Black)
                .fontWeight(FontWeight.Normal)
                .onClick(() => {
                  this.indicatorIndex = index
                  this.scrollIntoView(index)
                })
            }
            .padding({
              left: 12,
              right: 12,
              top: 8,
              bottom: 8
            })
            .margin({ left: 5, right: 5 })
            .borderRadius(20)
            .id(index.toString())
            .backgroundColor(this.indicatorIndex === index ? "#f1f9fe" : "#f7f7f7")
            .border({
              width: 1,
              color: this.indicatorIndex === index ? "#3ca4dc" : "#f7f7f7"
            })
          }, (item: string) => item)
        }
      }
      .width('100%')
      .height('100%')
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)
      .edgeEffect(EdgeEffect.None)
    }
  }
}
分享
微博
QQ
微信
回复
2025-07-28 09:57:38
相关问题
HarmonyOS tab组件的该怎么实现
843浏览 • 1回复 待解决
希望Tabs的位置是否支持自定义
1371浏览 • 1回复 待解决
DevEco Studio如何打开多行
1962浏览 • 1回复 待解决