Problem Description
How to execute custom methods when scrolling to the top and continuing to drag down, and when scrolling to the bottom and continuing to drag up?
Background Knowledge
Scrollable container component that allows content to be scrolled when the layout size of child components exceeds the size of the parent component.
-
- currentOffset retrieves the current scroll offset.
- isAtEnd checks whether the Scroll has reached the bottom.
PanGesture can bind swipe gesture events to components, where the event.offsetY in the gesture callback is positive when swiping from top to bottom, and negative otherwise.
Solution
Use PanGesture to bind the pan event to the Scroll, and determine the Scroll position in the onActionEnd method to perform corresponding processing when the sliding ends.
Scroll to the top and continue dragging downward to determine:
-
- Call
currentOffsetto get the current position of the scroll. If the Y value is less than or equal to 0, it means you have scrolled to the top.
- Determine whether to continue dragging downward based on the onActionEnd event. If event.offsetY is greater than 0, it indicates that the dragging should continue downward, and custom actions should be executed.
- Call
Scroll to the bottom and continue dragging up to determine:
-
- Call isAtEnd to determine whether the Scroll has reached the bottom.
- Determine whether to continue dragging upwards based on the onActionEnd event. If event.offsetY is less than 0, it indicates that the dragging should continue upwards, and then perform custom operations.
@Entry
@Component
struct ScrollDemo {
private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical })
private scrollerForScroll: Scroller = new Scroller()
build() {
Column() {
Scroll(this.scrollerForScroll) {
// Here, 'app.media.imageText' is just an example.
Image($r('app.media.imageText'))
.size({ width: 400, height: 1050 })
}
.width('100%')
.height('100%')
.edgeEffect(EdgeEffect.Spring)
.parallelGesture(
PanGesture(this.panOption)
.onActionStart((event: GestureEvent) => {
console.info('Pan start')
})
.onActionUpdate((event: GestureEvent) => {
// This method will be continuously triggered during the sliding process.
})
.onActionEnd((event: GestureEvent) => {
console.info('Pan end')
// Swipe to the bottom and keep swiping.
if (this.scrollerForScroll.isAtEnd() && event.offsetY < 0) {
console.info('Perform Custom Action 1')
}
// Swipe to the top and keep swiping.
const offsetRes = this.scrollerForScroll.currentOffset() // Get Scroll's current position
if (offsetRes.yOffset <= 0 && event.offsetY > 0) {
console.info('Perform Custom Action 2')
}
}), GestureMask.Normal)
}
}
}
Limitations or Considerations
- This example supports API Version 19 Release and later versions.
- This example supports HarmonyOS 5.1.1 Release SDK and later versions.
- This example requires DevEco Studio 5.1.1 Release or later for compilation.
Top comments (0)