美文网首页
鸿蒙开发自定义下拉刷新组件

鸿蒙开发自定义下拉刷新组件

作者: itfitness | 来源:发表于2024-03-28 16:57 被阅读0次

实现效果

案例源码

@Component
export struct RefreshView{
  @State marginTop:number = -80
  touchDownY:number = 0
  touchUpValue:number = -80
  private intervalId: number = 0

  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  private canRefresh:boolean = true

  build() {
    Column() {
      Image($r("app.media.git_refresh"))
        .width(80)
        .height(80)
        .margin({top:this.marginTop})
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item) => {
          ListItem() {
            Text('' + item)
              .width('100%').height(100).fontSize(16)
              .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
          }.backgroundColor(Color.White).borderRadius(10)
        }, item => item)
      }
      .listDirection(Axis.Vertical) // 排列方向
      .edgeEffect(EdgeEffect.Spring) // 滑动到边缘无效果
      .onScrollIndex((firstIndex: number, lastIndex: number) => {
        this.canRefresh = firstIndex == 0
        console.info('first' + firstIndex)
        console.info('last' + lastIndex)
      })
      .width('90%')
      .height('100%')
    }
    .backgroundColor($r("app.color.color_EEEEEE"))
    .onTouch((event: TouchEvent) => {
      if(this.canRefresh){
        if (event.type === TouchType.Down) {
          this.touchDownY = event.touches[0].y
        }
        if (event.type === TouchType.Up) {
          this.touchUpValue = this.marginTop
          if(this.marginTop < 0){
            this.stopRefresh()
          }else {
            setTimeout(()=>{
              this.stopRefresh()
            },2000)
          }
        }
        if (event.type === TouchType.Move) {
          this.marginTop = this.touchUpValue + event.touches[0].y - this.touchDownY
          if(this.marginTop >= 0){
            this.marginTop = 0
          }else if(this.marginTop <= -80){
            this.marginTop = -80
          }
        }
      }
    })
    .width('100%')
    .height('100%')
  }

  updateAnim = ()=>{
    this.marginTop = this.marginTop - 1
    if(this.marginTop <= -80){
      this.touchUpValue = -80
      clearInterval(this.intervalId)
    }
  }

  stopRefresh(){
    this.intervalId = setInterval(this.updateAnim,3)
  }

}

相关文章

网友评论

      本文标题:鸿蒙开发自定义下拉刷新组件

      本文链接:https://www.haomeiwen.com/subject/yooutjtx.html