HarmonyOS鸿蒙Next中scroll选中滚动居中

HarmonyOS鸿蒙Next中scroll选中滚动居中

scroll(){ row(){ foreach(数据源,()=>{布局builder}) } }

在scroll中如何点击某一项使其滚动到合适的位置,能滚动到中间的就滚动到中间,靠近两边的就使scroll滚动到相应边缘

2 回复

开发者你好,为更好的解决你的问题,需要你这边提供下更详细的ui效果图,动图最好。

下面有个代码案例,不太清楚是否符合你的要求,如果不符合要求,建议提供下完整的ui效果图 文字描述可能不是很好理解

@Entry
@Component
struct Index {
  scroller: Scroller = new Scroller;
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  @State itemHeights: number[] = new Array(16).fill(200)
  private containerHeight: number = 800

  build() {
    Scroll(this.scroller) {
      Column() {
        ForEach(this.arr, (item: number, index) => {
          Text(item.toString())
            .width('90%')
            .height(200)
            .backgroundColor(0xFFFFFF)
            .borderWidth(1)
            .borderColor(Color.Black)
            .borderRadius(15)
            .fontSize(16)
            .textAlign(TextAlign.Center)
            .onClick(() => {
              this.scrollToTarget(index)
            })
        }, (item: string) => item)
      }.width('100%').backgroundColor(0xDCDCDC)
    }
    .backgroundColor(Color.Yellow)
    .height(this.containerHeight)
    .edgeEffect(EdgeEffect.Spring)
    .scrollSnap({snapAlign:ScrollSnapAlign.CENTER, snapPagination: 100})
  }

  scrollToTarget(clickIndex: number) {
    // 计算累计偏移量
    let totalOffset = 0;
    for (let i = 0; i < clickIndex; i++) {
      totalOffset += this.itemHeights[i] || 0;
    }

    // 判断目标位置是否在中间区域
    const targetMiddle = totalOffset + (this.itemHeights[clickIndex] / 2);
    const visibleStart = this.scroller.currentOffset().yOffset
    const visibleEnd = visibleStart + this.containerHeight;

    if (targetMiddle > visibleStart + 100 && targetMiddle < visibleEnd - 100) {
      // 无需滚动(已在可视区)
      return;
    } else if (clickIndex === 0) {
      this.scroller.scrollEdge(Edge.Top); // 滚动到顶部
    } else if (clickIndex === this.itemHeights.length - 1) {
      this.scroller.scrollEdge(Edge.Bottom); // 滚动到底部
    } else {
      // 计算居中位置
      const centerOffset = totalOffset - (this.containerHeight / 2) + (this.itemHeights[clickIndex] / 2);
      this.scroller.scrollTo({
        xOffset: 0,
        yOffset: centerOffset,
        animation: { duration: 300, curve: Curve.EaseOut } // 平滑动画
      });
    }
  }
}

更多关于HarmonyOS鸿蒙Next中scroll选中滚动居中的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,实现滚动选中项居中的效果,可以通过ScrollViewListContainer组件结合布局和逻辑控制来实现。具体步骤包括:

  1. 使用ScrollView:通过计算选中项的位置,动态调整ScrollView的滚动位置,使用scrollTo方法实现居中。

  2. 使用ListContainer:通过ListContainerscrollToPosition方法,结合布局管理器(如LinearLayoutManager)计算选中项的位置,确保其在视图中居中。

  3. 布局调整:确保布局中选中项的高度和位置能够准确计算,以便正确居中。

这种方法可以有效提升用户体验,使选中项在滚动时自动居中显示。

回到顶部