HarmonyOS 鸿蒙Next list组件如何实现拖动排序功能和动画

HarmonyOS 鸿蒙Next list组件如何实现拖动排序功能和动画 list组件如何实现拖动排序功能和动画?

2 回复

可以使用拖拽事件或者通过手势实现替代。 1:拖拽事件: 文档地址: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-events-drag-drop-V5 2:手势实现拖动:

import curves from '@ohos.curves';
// xxx.ets
class ListItemModify implements AttributeModifier<ListItemAttribute> {
  public hasShadow: boolean = false
  public scale: number = 1
  public offsetY: number = 0
  applyNormalAttribute(instance: ListItemAttribute): void {
    if (this.hasShadow) {
      instance.shadow({ radius: 70, color: '#15000000', offsetX: 0, offsetY: 0 })
      instance.zIndex(1)
    }
    instance.scale({ x: this.scale, y: this.scale })
    instance.translate({ y: this.offsetY })
  }
}
enum DragSortState {
  IDLE,
  PRESSING,
  MOVING,
  DROPPING,
}
@Observed
class DragSortCtrl<T> {
  private arr: Array<T>
  private modify: Array<ListItemModify>
  private dragRefOffset: number = 0
  offsetY: number = 0
  state:DragSortState = DragSortState.IDLE
  private ITEM_INTV: number = 120
  constructor(arr:Array<T>, intv:number) {
    this.arr = arr;
    this.modify = new Array<ListItemModify>()
    this.ITEM_INTV = intv
    arr.forEach(() =>{
      this.modify.push(new ListItemModify())
    })
  }
  itemMove(index: number, newIndex: number): void {
    let tmp = this.arr.splice(index, 1)
    this.arr.splice(newIndex, 0, tmp[0])
    let tmp2 = this.modify.splice(index, 1)
    this.modify.splice(newIndex, 0, tmp2[0])
  }
  onLongPress(item: T): void {
    let index = this.arr.indexOf(item)
    this.dragRefOffset = 0
    animateTo({ curve: Curve.Friction, duration: 300 }, () => {
      this.state = DragSortState.PRESSING
      this.modify[index].hasShadow = true
      this.modify[index].scale = 1.05
    })
  }
  onDrop(item: T):void {
    let index = this.arr.indexOf(item)
    this.dragRefOffset = 0
    this.offsetY = 0
    animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
      this.state = DragSortState.DROPPING
      this.modify[index].hasShadow = false
      this.modify[index].offsetY = 0
      if (index < this.modify.length - 1) {
        this.modify[index + 1].scale = 1;
      }
      if (index > 0) {
        this.modify[index - 1].scale = 1;
      }
    })
    animateTo({curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150}, ()=>{
      this.state = DragSortState.IDLE
      this.modify[index].scale = 1
    })
  }
  onMove(item: T, offset: number) {
    this.state = DragSortState.MOVING
    this.offsetY = offset - this.dragRefOffset
    let index = this.arr.indexOf(item)
    this.modify[index].offsetY = this.offsetY
    let curveValue = curves.initCurve(Curve.Sharp)
    if (this.offsetY < 0) {
      let value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV)
      if (index < this.modify.length - 1) {
        this.modify[index + 1].scale = 1;
      }
      if (index > 0) {
        this.modify[index - 1].scale = 1 - value / 20;
      }
    } else if (this.offsetY > 0) {
      let value = curveValue.interpolate(this.offsetY / this.ITEM_INTV)
      if (index < this.modify.length - 1) {
        this.modify[index + 1].scale = 1 - value / 20;
      }
      if (index > 0) {
        this.modify[index - 1].scale = 1;
      }
    }
    if (this.offsetY > this.ITEM_INTV / 2) {
      animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
        this.offsetY -= this.ITEM_INTV
        this.dragRefOffset += this.ITEM_INTV
        this.modify[index].offsetY = this.offsetY
        this.itemMove(index, index + 1)
      })
    } else if (this.offsetY < -this.ITEM_INTV / 2) {
      animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
        this.offsetY += this.ITEM_INTV
        this.dragRefOffset -= this.ITEM_INTV
        this.modify[index].offsetY = this.offsetY
        this.itemMove(index, index - 1)
      })
    }
  }
  getModify(item:T):ListItemModify {
    let index = this.arr.indexOf(item)
    return this.modify[index]
  }
}

@Entry
@Component
struct ListItemExample {
  @State private arr: Array<number> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  @State dragSortCtrl: DragSortCtrl<number> = new DragSortCtrl<number>(this.arr, 120)
  build() {
    Stack() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text('' + item)
              .width('100%')
              .height(100)
              .fontSize(16)
              .fontColor(Color.Black)
              .textAlign(TextAlign.Center)
              .backgroundColor(0xFFFFFF)
          }
          .clip(true)
          .attributeModifier(this.dragSortCtrl.getModify(item))
          .borderRadius(10)
          .margin({ left: 12, right: 12 })
          .gesture(
            // 以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件
            GestureGroup(GestureMode.Sequence,
              LongPressGesture({ repeat: false })
                .onAction((event?: GestureEvent) => {
                  this.dragSortCtrl.onLongPress(item)
                }),
              PanGesture({ fingers: 1, direction: null, distance: 0 })
                .onActionUpdate((event: GestureEvent) => {
                  this.dragSortCtrl.onMove(item, event.offsetY)
                })
                .onActionEnd((event: GestureEvent) => {
                  this.dragSortCtrl.onDrop(item)
                })
            )
              .onCancel(() => {
                this.dragSortCtrl.onDrop(item)
              })
          )
        }, (item: number) => item.toString())
      }
    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
  }
}

更多关于HarmonyOS 鸿蒙Next list组件如何实现拖动排序功能和动画的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS中,List组件的拖动排序功能和动画可以通过@ohos.ability.featureAbility模块中的List组件结合@ohos.animator模块来实现。具体步骤如下:

  1. 启用拖动排序:使用List组件的onItemDragStartonItemDrop事件来监听拖动的开始和结束。onItemDragStart事件在用户开始拖动列表项时触发,onItemDrop事件在用户释放拖动项时触发。通过这两个事件,可以获取拖动的起始位置和目标位置,并在数据源中交换这两个位置的数据。

  2. 更新列表数据:在onItemDrop事件中,更新List组件的数据源,并调用Listrefresh方法来刷新列表显示。

  3. 添加动画效果:使用@ohos.animator模块中的Animator类来为列表项的移动添加动画效果。可以在onItemDrop事件中,为目标位置和起始位置的列表项分别创建动画,使其平滑移动到新的位置。

  4. 处理边界情况:在实现拖动排序时,需要处理边界情况,例如拖动到列表的顶部或底部时,确保列表项能够正确滚动。

以下是一个简单的代码示例:

import { List, ListItem } from '@ohos.ability.featureAbility';
import { Animator } from '@ohos.animator';

// 假设有一个列表数据源
let dataSource = [...];

// 创建List组件
let list = new List({
  dataSource: dataSource,
  onItemDragStart: (event) => {
    // 获取拖动的起始位置
    let startIndex = event.index;
  },
  onItemDrop: (event) => {
    // 获取拖动的目标位置
    let targetIndex = event.index;

    // 交换数据源中的位置
    [dataSource[startIndex], dataSource[targetIndex]] = [dataSource[targetIndex], dataSource[startIndex]];

    // 刷新列表
    list.refresh();

    // 创建动画
    let animator = new Animator({
      duration: 300,
      curve: 'easeInOut'
    });

    // 为起始位置和目标位置的列表项添加动画
    animator.start();
  }
});
回到顶部