HarmonyOS鸿蒙Next中怎么监听Scroll的滑动百分比,想关联Progress进度条

HarmonyOS鸿蒙Next中怎么监听Scroll的滑动百分比,想关联Progress进度条

Scroll是固定宽度的

Scroll() {
  
}
.height('100%')
.scrollable(ScrollDirection.Horizontal)
.width(600)
试过很多方法了不好用,经常有-数 监听不准
7 回复

使用 onDidScroll 事件(API version 12+)实时获取滚动偏移量,并基于总滚动范围计算进度:

@State scrollYOffset: number = 0; // 记录垂直偏移量
@State totalScrollHeight: number = 0; // 总可滚动高度(需通过子组件计算)

Scroll() {
  Column() { /* 子组件内容 */ }
  .onAppear(() => {
    // 获取子组件总高度(示例)
    const rect = componentUtils.getRectangleById('childComponentId');
    this.totalScrollHeight = rect.height - Scroll容器高度;
  })
}
.onDidScroll((xOffset: number, yOffset: number) => {
  this.scrollYOffset = yOffset;
  const progress = this.scrollYOffset / this.totalScrollHeight;
  console.log(`滑动进度:${progress}`);
})

总滚动范围 = 子组件高度 - Scroll容器高度,需通过 componentUtils 动态获取子组件尺寸。

需结合布局完成后的回调(如 onAppear)确保准确获取子组件尺寸。

更多关于HarmonyOS鸿蒙Next中怎么监听Scroll的滑动百分比,想关联Progress进度条的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


使用 ScrollOnScrollCallback 监听滚动事件,通过 xOffset 参数获取水平偏移量。内容向左滚动时偏移量为正,向右为负,单位为 vp 。

@Entry
@Component

struct Index {

  @State progress: number = 0 // 进度值

  private totalWidth: number = 1200 // 滚动内容总宽度(需根据实际内容替换)

  private scrollWidth: number = 600 // Scroll容器宽度

  // 滚动事件回调
  onScroll(xOffset: number) {
    const maxOffset = this.totalWidth - this.scrollWidth

    // 计算百分比(取绝对值处理负数)
    this.progress = Math.abs(xOffset) / maxOffset * 100
  }

  build() {

    Scroll() {

      // 滚动内容(需确保总宽度大于容器宽度)
      Row() { /* 你的实际内容 */ }

        .width(this.totalWidth)

    }
    .height('100%')
    .width(this.scrollWidth)
    .scrollable(ScrollDirection.Horizontal)
    .onDidScroll((xOffset: number) => {

      this.onScroll(xOffset)

    })

    Progress({ value: this.progress })

  }
}

目前没有哪一个滚动的容器组件能够实现渲染后直接获取到容器的总高度和百分比,这个功能可以提工单,给官方提需求,以后有机会加上,楼主的这个需求也是有替代方法的

  1. 使用上面楼主的方法通过里面已知的组件的高度来计算,会涉及很多计算、考虑全面一点的话这个功能也是容易实现的

  2. 使用ScrollBar,自定义ScrollBar样式再增加一个遮盖层来实现想要的样式ScrollBar和scroll绑定过后就能获取到整体的高度,虽然拿不到值但是样式上是类似于进度条的

参考文档:ScrollBar-滚动与滑动-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者

示例代码:

import { ColorMetrics } from '@kit.ArkUI'
@Component
struct ScrollBarExample {
  private scroller: Scroller = new Scroller();
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
  @State scrollBarColor:ColorMetrics = ColorMetrics.rgba(24, 35, 48, 0.4);

  build() {
    Column() {
      Stack({ alignContent: Alignment.End }) {
        Scroll(this.scroller) {
          Flex({ direction: FlexDirection.Column }) {
            ForEach(this.arr, (item: number) => {
              Row() {
                Text(item.toString())
                  .width('80%')
                  .height(60)
                  .backgroundColor('#3366CC')
                  .borderRadius(15)
                  .fontSize(16)
                  .textAlign(TextAlign.Center)
                  .margin({ top: 5 })
              }
            }, (item:number) => item.toString())
          }
          .margin({ right: 15 })
        }
        .width('90%')
        .scrollBar(BarState.Off)
        .scrollable(ScrollDirection.Vertical)
        ScrollBar({ scroller: this.scroller, direction: ScrollBarDirection.Vertical,state: BarState.Auto })
          .scrollBarColor(this.scrollBarColor)
      }
    }
  }
}

1、获取Scroll内部组件的高度/宽度,使用.onAreaChange()方法即可

2、获取当前位置,使用currentOffset获取当前滚动偏移量

3、当前位置/scroll内部总高度 * 100%就是百分比了

  1. 获取 Scroll 的关键参数:

    • 已知 Scroll 是固定宽度(设为scrollWidth)。
    • 内容总宽度(contentWidth)可通过 Scroll 的滚动范围获取(内容宽度 = Scroll 宽度 + 可滚动距离)。
    • 总可滚动距离 = contentWidth - scrollWidth(内容超出 Scroll 的部分)。
  2. 监听滚动事件:

    通过 Scroll 的onScroll事件获取实时滚动距离(scrollX,水平滚动时)。

  3. 计算滑动百分比:

    百分比 =(当前滚动距离 / 总可滚动距离)× 100%(需处理总可滚动距离为 0 的边界情况)。

  4. 关联 Progress 进度条:

    将计算出的百分比绑定到 Progress 组件的value属性。

在HarmonyOS Next中监听Scroll滑动百分比可以使用ScrollViewonScroll回调。以下是关键代码示例:

import { ScrollView, Progress } from '@ohos.ui';

let scrollView = new ScrollView();
let progress = new Progress();

scrollView.onScroll((xOffset: number, yOffset: number) => {
  let contentHeight = scrollView.getContentSize().height;
  let viewHeight = scrollView.getHeight();
  let scrollableHeight = contentHeight - viewHeight;
  let percentage = yOffset / scrollableHeight;
  
  progress.setProgress(percentage * 100);
});

通过计算yOffset与可滚动高度的比值获取百分比,然后设置Progress进度条的值。

在HarmonyOS Next中监听Scroll滑动百分比并关联Progress进度条,可以通过以下方式实现:

  1. 使用Scroll组件的onScrollFrame回调获取精确的滚动位置:
Scroll() {
  // 你的内容
}
.width(600)
.scrollable(ScrollDirection.Horizontal)
.onScrollFrame((offset: number) => {
  // offset是当前滚动位置
  const maxScroll = 600 - scrollWidth; // 计算最大可滚动距离
  const percentage = Math.max(0, Math.min(1, offset / maxScroll)); // 确保在0-1范围内
  progressBar.value = percentage * 100; // 更新进度条
})
  1. 处理边界情况:
  • 使用Math.max/min确保百分比在0-100%之间
  • 在onScrollFrame中处理负值问题
  1. 性能优化建议:
  • 避免在滚动回调中执行耗时操作
  • 使用debounce减少频繁更新

注意:确保scrollWidth是Scroll内容的总宽度减去可视宽度(600),这样才能正确计算百分比。

回到顶部