更新升级 专属应用 系统故障 硬件故障 电脑汽车 鸿蒙刷机 鸿蒙开发Linux教程 鸿蒙开发Linux命令
当前位置:HMXT之家 > 应用开发 > 在鸿蒙ArkUI(eTS)开发中,实现列表的上拉加载功能

在鸿蒙ArkUI(eTS)开发中,实现列表的上拉加载功能

更新时间:2021-12-22 16:25:44浏览次数:373+次

在鸿蒙ArkUI(eTS)开发中,如何实现列表的上拉加载功能?

\

解答

主要通过onScrollIndex()方法判断List组件是否滑动到底部,然后通过是否正在加载、是否还有数据两个变量状态判断是否需要加载新的数据。代码如下:

import prompt from '@system.prompt'

@Entry

@Component

struct Index {

  @State private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

  @State isLoading:boolean=false;

  @State hasData:boolean=true;

  build() {

    Stack() {

      List() {

        ForEach(this.arr, (item) => {

          ListItem() {

            Text('' + item)

              .width('100%')

              .height(100)

              .fontSize(16)

              .textAlign(TextAlign.Center)

              .borderRadius(10)

              .backgroundColor(0xFFFFFF)

          }.editable(true)

        }, item => item)

        if(!this.hasData){

          ListItem() {

            Text('没有更多数据了')

              .width('100%')

              .height(40)

              .fontSize(16)

              .textAlign(TextAlign.Center)

              .backgroundColor(0xCECECE)

          }

        }else {

          if (this.isLoading && this.hasData) {

            ListItem() {

              Text('正在加载数据')

                .width('100%')

                .height(40)

                .fontSize(16)

                .textAlign(TextAlign.Center)

                .backgroundColor(0xFFFFFF)

            }

          }

        }

      }

      .divider({ strokeWidth: 1, color: 0xcdcdcd}) // 每行之间的分界线

      .edgeEffect(EdgeEffect.None) // 滑动到边缘无效果

      .onScrollIndex((firstIndex: number, lastIndex: number) => {

        if(this.hasData&&!this.isLoading&&lastIndex>=this.arr.length-1){

          this.isLoading=true;

          this.loadMoreData();

        }

        console.info('first' + firstIndex+'    last' + lastIndex)

      })

      .width('100%')

    }.width('100%').height('100%').backgroundColor(0xDCDCDC)

  }

  loadMoreData(){

    prompt.showToast({

      message: "加载数据"

    });

    setTimeout(() => {

      this.isLoading = false

      this.arr.push(21, 22, 23, 24, 25, 26, 27, 28, 29, 30)

      this.hasData=false;

    }, 3000);

  }}

相关参考:鸿蒙开发怎样根据手机横竖屏判断加载不同布局