ohos_pull_to_refresh:基于OpenHarmony的下拉刷新上拉加载组件项目

用户可在OpenHarmony应用中实现列表下拉刷新和上拉加载功能,该项目支持内置动画属性设置、自定义动画及lazyForEach数据源,适配List、Scroll等系统容器组件。

Branch2Tags25

pulltorefresh

Introduction

PullToRefresh is a pull-to-refresh and pull-up-to-load-more component for OpenHarmony ArkUI. It supports built-in animation configuration, custom animations, and LazyForEach data sources.

Demo

Built-in animation effects

Refresh LoadMore

Installation

ohpm install @ohos/pulltorefresh

For more information about OpenHarmony ohpm environment configuration, please refer to How to install OpenHarmony ohpm packages.

Constraints and Limitations

Compatibility

Verified in the following versions:

  • DevEco Studio: NEXT Beta1-5.0.3.806, SDK: API12 Release(5.0.0.66), ROM: 5.0.0.66

Usage Limitations

  1. Currently only supports List, Scroll, Tabs, Grid, and WaterFlow system container components
  2. Temporarily does not support setting spring effect and shadow effect of system container components. When using, set the value of the edgeEffect attribute of the system component to EdgeEffect.None
  3. Temporarily does not support automatically triggering pull-up to load more function when the page reaches the bottom
  4. Temporarily does not support triggering pull-up to load more function when page data does not fill one screen
  5. Temporarily does not support triggering pull-down refresh function through code
  6. Temporarily does not support providing a gesture end callback when the pull-down refresh animation ends

Usage Example

// Usage with @Component
import { PullToRefresh } from '@ohos/pulltorefresh'

// Create a scroller instance.
private scroller: Scroller = new Scroller();
  
PullToRefresh({
  // (Mandatory) Data source of the list component.
  data: $data,
  // (Mandatory) List or grid component in the main layout.
  scroller: this.scroller,
  // (Mandatory) Custom list or grid view.
  customList: () => {
    // A UI method decorated by @Builder.
    this.getListView();
  },
  // (Optional) Callback used to handle the pull-down refresh action.
  onRefresh: () => {
    return new Promise<string>((resolve, reject) => {
      // Simulate a network request operation. When data is obtained 2 seconds after the network request, inform the component to refresh the list data.
      setTimeout(() => {
        resolve ('Refresh successful');
        this.data = [...this.dataNumbers];
      }, 2000);
    });
  },
  // (Optional) Callback used to handle the pull-up loading action.
  onLoadMore: () => {
    return new Promise<string>((resolve, reject) => {
      // Simulate a network request operation. When data is obtained 2 seconds after the network request, inform the component to update the list data.
      setTimeout(() => {
        resolve('');
        this.data.push ("Added items" + this.data.length);
      }, 2000);
    });
  },
  customLoad: null,
  customRefresh: null,
})
  
// Usage with @ComponentV2
import { PullToRefreshV2 } from '@ohos/pulltorefresh'

// Create a scroller instance.
private scroller: Scroller = new Scroller();

PullToRefreshV2({
  // (Optional) Data source of the list component.
  data: this.data,
  // (Mandatory) List or grid component in the main layout.
  scroller: this.scroller,
  // (Mandatory) Custom list or grid view.
  customList: () => {
    // A UI method decorated by @Builder.
    this.getListView();
  },
  // (Optional) Callback used to handle the pull-down refresh action.
  onRefresh: () => {
    return new Promise<string>((resolve, reject) => {
      // Simulate a network request operation. When data is obtained 2 seconds after the network request, inform the component to refresh the list data.
      setTimeout(() => {
        resolve ('Refresh successful');
        this.data = [...this.dataNumbers];
      }, 2000);
    });
  },
  // (Optional) Callback used to handle the pull-up loading action.
  onLoadMore: () => {
    return new Promise<string>((resolve, reject) => {
      // Simulate a network request operation. When data is obtained 2 seconds after the network request, inform the component to update the list data.
      setTimeout(() => {
        resolve('');
        this.data.push ("Added items" + this.data.length);
      }, 2000);
    });
  },
  customLoad: null,
  customRefresh: null,
})

For more examples, please see example code.

bindSheet Pull-Down Dismiss

When PullToRefresh is used inside a half-modal bindSheet and the sheet needs to be dismissed by pulling down, disable pull-down refresh with the existing configuration: new PullToRefreshConfigurator().setHasRefresh(false). After pull-down refresh is disabled, the component handles only pull-up loading gestures and does not intercept downward pan gestures.

ArkUI also requires the scrollable container in the sheet to configure nestedScroll. PullToRefresh / PullToRefreshV2 provide the boolean property enableNestedScroll. When set to true, the internal main Scroll applies the default nestedScroll configuration (scrollForward and scrollBackward are both NestedScrollMode.SELF_FIRST).

private refreshConfigurator = new PullToRefreshConfigurator()
  .setHasRefresh(false);

PullToRefresh({
  data: $data,
  scroller: this.scroller,
  enableNestedScroll: true,
  refreshConfigurator: this.refreshConfigurator,
  customList: () => { this.getContentView(); },
  // ...
})

See pages/bindSheetPullRefresh.ets in the entry module for a full sample.

Note: Pull-down refresh and pull-down sheet dismissal both use downward gestures. In sheet-dismiss scenarios, disable pull-down refresh (setHasRefresh(false)). Pull-up loading uses an upward gesture and is not affected; it remains functional via Scroll.onReachEnd when enableNestedScroll is enabled. setHasRefresh(false) does not enable nested scrolling by itself. To coordinate nested scrolling between bindSheet and the internal Scroll, set enableNestedScroll: true. When enabled, pull-down gestures based on scroller are not handled; customList is wrapped by the internal Scroll, and do not bind the same scroller to another List, Scroll, or other scrollable container inside customList. V2 sample: pages/bindSheetPullRefreshV2.ets.

Usage Instructions

PullToRefresh Component (@Component)

The PullToRefresh component wraps List, Scroll, Tabs, Grid, or WaterFlow components to provide pull-down refresh and pull-up load-more functionality.

PullToRefreshV2 Component (@ComponentV2)

PullToRefreshV2 provides the same refresh and load-more capabilities as PullToRefresh and targets @ComponentV2 state management.

LazyForEach Data Source Support

LazyForEach iterates data on demand from the provided data source and creates corresponding components during each iteration. When LazyForEach is used in a scroll container, the framework creates components on demand according to the visible area of the scroll container. When a component slides out of the visible area, the framework destroys and recycles the component to reduce memory usage.

Interface Description:

LazyForEach(
    dataSource: IDataSource,             // Data source for data iteration
    itemGenerator: (item: any, index?: number) => void,  // Subcomponent generation function
    keyGenerator?: (item: any, index?: number) => string // Key generation function
): void

IDataSource Type Description

interface IDataSource {
    totalCount(): number; // Get total number of data
    getData(index: number): Object; // Get data corresponding to index value
    registerDataChangeListener(listener: DataChangeListener): void; // Register data change listener
    unregisterDataChangeListener(listener: DataChangeListener): void; // Unregister data change listener
}

DataChangeListener Type Description

interface DataChangeListener {
    onDataReloaded(): void; // Called when data is reloaded
    onDataAdded(index: number): void; // Called when data is added
    onDataMoved(from: number, to: number): void // Called when data move start position and data move target position are swapped
    onDataDeleted(index: number): void; // Called when data is deleted
    onDataChanged(index: number): void; // Called when data is changed
    onDataAdd(index: number): void; // Called when data is added
    onDataMove(from: number, to: number): void // Called when data move start position and data move target position are swapped
    onDataDelete(index: number): void; // Called when data is deleted
    onDataChange(index: number): void; // Called when data is changed
}

For specific usage, please refer to the OpenHarmony official documentation: LazyForEach: Data Lazy Loading

API Reference

PullToRefresh / PullToRefreshV2 Component Properties

Property Type Description Default Required OpenHarmony Platform Support
data Object[] | undefined Data bound to the list or grid component undefined Yes for PullToRefresh; No for PullToRefreshV2 Yes
scroller Scroller Scroller object bound to the list or grid component undefined Yes Yes
customList () => void Custom main layout, containing list or grid component undefined Yes Yes
enableNestedScroll boolean Whether to enable the built-in nested scroll mode; when enabled, the main area uses Scroll and applies the default nestedScroll configuration (scrollForward and scrollBackward are both NestedScrollMode.SELF_FIRST). Pull-down refresh is disabled; pull-up loading is supported via Scroll.onReachEnd false No Yes
refreshConfigurator PullToRefreshConfigurator Component property configuration PullToRefreshConfigurator No Yes
mWidth Length Container width undefined (adaptive) No Yes
mHeight Length Container height undefined (adaptive) No Yes
onRefresh () => Promise<string> Pull-down refresh callback End pull-down refresh animation after 1 second and prompt "Refresh failed" No Yes
onLoadMore () => Promise<string> Pull-up load more callback End pull-up load animation after 1 second No Yes
customRefresh () => void Custom pull-down refresh animation layout undefined No Yes
onAnimPullDown (value?: number, width?: number, height?: number) => void | undefined Pulling down callback undefined No Yes
onAnimRefreshing (value?: number, width?: number, height?: number) => void | undefined Refreshing callback undefined No Yes
customLoad () => void Custom pull-up load animation layout undefined No Yes
onAnimPullUp (value?: number, width?: number, height?: number) => void | undefined Pulling up callback undefined No Yes
onAnimLoading (value?: number, width?: number, height?: number) => void | undefined Loading callback undefined No Yes

PullToRefreshConfigurator Configuration Class

Method Parameter Return Value Description Required OpenHarmony Platform Support
setHasRefresh hasRefresh: boolean this Set whether to have pull-down refresh function No Yes
setHasLoadMore hasLoadMore: boolean this Set whether to have pull-up load more function No Yes
setMaxTranslate maxTranslate: number this Set the maximum distance for pull-down and pull-up No Yes
setSensitivity sensitivity: number this Set pull-down and pull-up sensitivity No Yes
setListIsPlacement listIsPlacement: boolean this Set whether the list returns to position after sliding ends No Yes
setAnimDuration animDuration: number this Set the execution time of the rebound animation after sliding ends No Yes
setRefreshHeight refreshHeight: number this Set pull-down animation height No Yes
setRefreshColor refreshColor: string this Set pull-down animation color No Yes
setRefreshBackgroundColor refreshBackgroundColor: ResourceColor this Set pull-down animation area background color No Yes
setRefreshTextColor refreshTextColor: ResourceColor this Set font color of prompt text after pull-down load completes No Yes
setRefreshTextSize refreshTextSize: number | string | Resource this Set font size of prompt text after pull-down load completes No Yes
setRefreshAnimDuration refreshAnimDuration: number this Set the execution time of one pull-down animation, effective only when using custom pull-down refresh animation No Yes
setRefreshCompleteTextHoldTime refreshCompleteTextHoldTime: number this Set the hold time of refresh success text after pull-down refresh completes No Yes
setLoadImgHeight loadImgHeight: number this Set the height of the image in pull-up animation No Yes
setLoadBackgroundColor loadBackgroundColor: ResourceColor this Set pull-up animation area background color No Yes
setLoadTextColor loadTextColor: ResourceColor this Set font color of pull-up text No Yes
setLoadTextSize loadTextSize: number | string | Resource this Set font size of pull-up text No Yes
setLoadTextPullUp1 loadTextPullUp1: ResourceStr this Set pull-up stage 1 text No Yes
setLoadTextPullUp2 loadTextPullUp2: ResourceStr this Set pull-up stage 2 text No Yes
setLoadTextLoading loadTextLoading: ResourceStr this Set text when pull-up loading more No Yes

About Obfuscation

For code obfuscation, please refer to Code Obfuscation Introduction.

If you want to pulltorefresh library not to be obfuscated during code obfuscation, you need to add the corresponding exclusion rule in the obfuscation rules configuration file obfuscation-rules.txt:

-keep
./oh_modules/@ohos/pulltorefresh

Directory Structure

ohos_pull_to_refresh
├── entry/           # Example code directory
│   └── src/
│       └── main/
│           ├── ets/
│           │   └── pages/  # Example pages
│           ├── module.json5
│           └── resources/
├── library/         # Core code directory
│   ├── index.ets    # Export entry file
│   └── src/
│       └── main/
│           └── ets/
│               └── components/
│                   └── PullToRefresh/  # Component implementation
├── gifs/            # Demo images
├── build-profile.json5
├── oh-package.json5
├── hvigorfile.js
└── README_zh.md

Contributing

If you find any issues during use, please submit Issues to the component. You are also very welcome to submit PRs to contribute.

License

This project is based on Apache License 2.0. Please feel free to enjoy and participate in open source.

Introduction

用户可在OpenHarmony应用中实现列表下拉刷新和上拉加载功能,该项目支持内置动画属性设置、自定义动画及lazyForEach数据源,适配List、Scroll等系统容器组件。

Customize your domain