怎么监听Scroll的滑动百分比?

0 评论 19 浏览 0 收藏 4 分钟

本问答帖原创发布在华为开发者联盟社区 ,欢迎开发者前往论坛提问交流。

更多与该问题相关的讨论,请点击原帖查看:

怎么监听Scroll的滑动百分比,想关联Progress进度条-华为开发者问答 | 华为开发者联盟 (huawei.com)

问题描述:

如何监听Scroll的滑动百分比?

解决方案:

【背景知识】

在HarmonyOS中,onWillScroll和onDidScroll是滚动容器组件(如Scroll)的两个关键事件回调接口。

onWillScroll在滚动行为‌即将发生前‌触发,属于滚动流程的‌前置回调‌,主要用于滚动行为的前置拦截‌(例如通过返回值控制是否允许滚动)。

onDidScroll‌在滚动行为‌完成一帧滑动后‌触发,属于滚动流程的‌后置回调‌,用于监听当前帧滑动的偏移量和当前滑动状态。

【解决方案】

使用onDidScroll‌或onWillScroll都可实现监听滚动,参考滚动监听。如下demo为使用onDidScroll监听滚动:

// Index.ets

@Entry

@Component

struct Index {

@State message: string = 'Hello World';

@State tabArray: Array<number> = [0, 1, 2, 3, 4]

@State value: number = 0

private scroller: Scroller = new Scroller()

totalHeight: number = 0

scrollHeight: number = 0

aboutToAppear(): void {

this.totalHeight = 200 * 5

this.scrollHeight = 600

}

build() {

Column() {

Column() {

Progress({ value: 0, total: this.totalHeight - this.scrollHeight, type: ProgressType.Linear })

.color(Color.Blue)

.value(this.value)

.width(300)

.height(20)

}.height(100).alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Center)

Scroll(this.scroller) {

Column() {

ForEach(this.tabArray, (item: number) => {

ListItem() {

Column() {

Text("页签" + item + "_111111").fontSize(40)

Text("页签" + item + "_222222").fontSize(40)

Text("页签" + item + "_333333").fontSize(40)

}.width("100%")

.height(200)

.backgroundColor(Color.Gray)

}

}, (item: string) => item)

}.width("100%")

}

.scrollable(ScrollDirection.Vertical)

.edgeEffect(EdgeEffect.None)

.onDidScroll((xOffset: number, yOffset: number, scrollState: ScrollState) => {

this.value += yOffset

console.info("this.value = " + this.value)

})

.height(this.scrollHeight)

}

.height('100%')

.width('100%')

}

}

 

▶更多实践干货就在华为开发者联盟

▶扫码加入鸿蒙主题交流群,共同交流鸿蒙应用创新与开发

更多精彩内容,请关注人人都是产品经理微信公众号或下载App
评论
评论请登录
  1. 目前还没评论,等你发挥!