HarmonyOS 有两个Grid,如何把item从一个Grid拖入另一个Grid?

如题:HarmonyOS 有两个Grid,如何把item从一个Grid拖入另一个Grid?

阅读 422
1 个回答

示例如下:

changeIndex(index1: number, index2: number) { //交换数组位置
  let numberArr: Array<string> = this.whoIsStart == 0 ? this.numbers : this.numbers1;
  let temp: string;
  temp = numberArr[index1] + "";
  if (this.whoIsStart == 0 && index2 != -1) {
    this.numbers[index1] = numberArr[index2];
    this.numbers[index2] = temp;
  } else if (this.whoIsStart == 1 && index2 != -1) {
    this.numbers1[index1] = numberArr[index2];
    this.numbers1[index2] = temp;
  }
  this.changeData = [];
  this.text = "";
  this.whoIsStart = -1;
}

第一个grid:

.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { //第一次拖拽此事件绑定的组件时,触发回调。
  if (this.whoIsStart == 1) {
    return;
  }
  this.text = this.numbers[itemIndex]
  this.whoIsStart = 0;
  this.changeData[0] = itemIndex;
  return this.pixelMapBuilder() //设置拖拽过程中显示的图片。
})
  .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number,
    isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
    // isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生
    if (this.whoIsStart == 1) {
      return;
    }
    if (!isSuccess || insertIndex >= this.numbers.length) {
      return
    }
    this.changeData[1] = insertIndex;
    this.changeIndex(this.changeData[0], this.changeData[1])
    console.info('beixiang 起点' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置
  })

第二个grid:

.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { //第一次拖拽此事件绑定的组件时,触发回调。
  if (this.whoIsStart == 0) return;
  this.text = this.numbers1[itemIndex]
  this.changeData[0] = itemIndex;
  this.whoIsStart = 1;
  return this.pixelMapBuilder() //设置拖拽过程中显示的图片。
})
  .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number,
    isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
    // isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生
    if (this.whoIsStart == 0) {
      return;
    }
    if (!isSuccess || insertIndex >= this.numbers.length) {
      return
    }
    this.changeData[1] = insertIndex;
    console.info('beixiang 终点' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置
    console.info('beixiang 终点' + this.changeData) //itemIndex拖拽起始位置,insertIndex拖拽插入位置
    this.changeIndex(this.changeData[0], this.changeData[1])
  })