【HarmonyOS NEXT】如何拖拽调整列表项顺序

 【关键字】

拖拽 / 列表 / List / ListItem / 排序 / 顺序

【问题描述】

如何拖拽调整列表项顺序,实现如下的效果。

cke_20134.pngcke_25121.png

当前示例代码如下:

import { WatchListItem, QuoteWatchListProxy } from '@winner/quote_service';
import { WatchListGroupItem } from '@winner/quote_service';
import { ThemeServiceProxy } from '@winner/resource';
import {
  JtBaseCustomDialogByOption,
  JtCommonDialogOption,
  JtWatchListGroupDialog,
  ListTab,
  TabBarWithButtonOptions
} from '@winner/widget';
import { JTToggle } from '@winner/widget/src/main/ets/base/JTToggle';
import { WatchListEditStockViewModel } from '@winner/quote_logic'
import CommonConstants from '@winner/widget/src/main/ets/constants/CommonConstants';
import promptAction from '@ohos.promptAction';

@Component
export struct DemoPag {

   watchList:Array<string> = new Array<string>()

  build() {
    Flex({ direction: FlexDirection.Column }) {

      Flex({ direction: FlexDirection.Row }) {
        Text("股票名称")
          .fontSize('14vp')
           .layoutWeight(1)
        Text("置顶")
          .fontSize('14vp')
          .align(Alignment.Center)
          .margin({ right: '40vp' })
        Text("拖动")
          .fontSize('14vp')
          .align(Alignment.End)
          .margin({ right: '16vp' })
      }.margin({ top: '11vp', bottom: '11vp', left: '16vp' })


      List() {
        ForEach(this.watchList, (item: string, index: number) => {
          ListItem() {
            Row() {
              Column() {

                Text(item)
                  .fontSize('14vp').width('100%')
                  .height('45vp')
                  .margin({ top: '4vp' })
              }.margin({ left: '8vp', top: '10vp', bottom: '10vp' }).alignItems(HorizontalAlign.Start).layoutWeight(1)
              Image($r('app.media.icon_move_to_top'))
                .align(Alignment.Center)
                .margin({ right: '40vp' })
                .width(36)
                .height(42)
                .draggable(false)
              Image($r('app.media.icon_24_edit_drag'))
                .align(Alignment.End)
                .margin({ right: '16vp' })
                .width(36)
                .height(42)
            }.width(CommonConstants.FULL_WIDTH).margin({ left: '16vp' })
          }.onDragStart(  (event: DragEvent, extraParams?: string)=>{
            return this.pixelMapBuilder(item)
          } )
          .width(CommonConstants.FULL_WIDTH)

        });
      }
      .chainAnimation(true)
      .divider({
        strokeWidth: '0.5vp',
        startMargin: '16vp',

      })
      .width(CommonConstants.FULL_WIDTH)
      .layoutWeight(1)
      .height('0vp')
      .layoutWeight(1)
      .divider({
        strokeWidth: '0.5vp',
        startMargin: '16vp',

      })

    }.width(CommonConstants.FULL_WIDTH).height(CommonConstants.FULL_HEIGHT)
  }



  @Builder
  pixelMapBuilder(item: string) {

    Text(item).width('200vp').height('200vp').fontSize('14vp').backgroundColor(Color.Red).fontColor(Color.White)
  }

  aboutToAppear() {
    for (let index = 0; index < 100; index++) {
       this.watchList[index] ="我是"+index

    }
  }

}
如果修改能实现上面的效果。

【解决方案】

可参考如下代码实现所需的拖拽效果:

import curves from '@ohos.curves';
import Curves from '@ohos.curves'
// xxx.ets
@Entry
@Component
struct ListItemExample {
@State private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State dragItem: number = -1
@State scaleItem: number = -1
@State neighborItem: number = -1
@State neighborScale: number = -1
private dragRefOffset: number = 0
@State offsetX: number = 0
@State offsetY: number = 0
private ITEM_INTV: number = 120
scaleSelect(item: number): number {
if (this.scaleItem == item) {
return 1.05
} else if (this.neighborItem == item) {
return this.neighborScale
} else {
return 1
}
}
itemMove(index: number, newIndex: number): void {
let tmp = this.arr.splice(index, 1)
this.arr.splice(newIndex, 0, tmp[0])
}
build() {
Stack() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
.shadow(this.scaleItem == item ? { radius: 70, color: '#15000000', offsetX: 0, offsetY: 0 } :
{ radius: 0, color: '#15000000', offsetX: 0, offsetY: 0 })
.animation({ curve: Curve.Sharp, duration: 300 })
}
.margin({ left: 12, right: 12 })
.scale({ x: this.scaleSelect(item), y: this.scaleSelect(item) })
.zIndex(this.dragItem == item ? 1 : 0)
.translate(this.dragItem == item ? { y: this.offsetY } : { y: 0 })
.gesture(
// 以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
.onAction((event?: GestureEvent) => {
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
this.scaleItem = item
})
})
.onActionEnd(() => {
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
this.scaleItem = -1
})
}),
PanGesture({ fingers: 1, direction: null, distance: 0 })
.onActionStart(() => {
this.dragItem = item
this.dragRefOffset = 0
})
.onActionUpdate((event: GestureEvent) => {
this.offsetY = event.offsetY - this.dragRefOffset
// console.log('Y:' + this.offsetY.toString())
this.neighborItem = -1
let index = this.arr.indexOf(item)
let curveValue = Curves.initCurve(Curve.Sharp)
let value: number = 0
//根据位移计算相邻项的缩放
if (this.offsetY < 0) {
value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV)
this.neighborItem = this.arr[index-1]
this.neighborScale = 1 - value / 20;
console.log('neighborScale:' + this.neighborScale.toString())
} else if (this.offsetY > 0) {
value = curveValue.interpolate(this.offsetY / this.ITEM_INTV)
this.neighborItem = this.arr[index+1]
this.neighborScale = 1 - value / 20;
}
//根据位移交换排序
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.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.itemMove(index, index - 1)
})
}
})
.onActionEnd((event: GestureEvent) => {
animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
this.dragItem = -1
this.neighborItem = -1
})
animateTo({
curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
}, () => {
this.scaleItem = -1
})
})
)
.onCancel(() => {
animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
this.dragItem = -1
this.neighborItem = -1
})
animateTo({
curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
}, () => {
this.scaleItem = -1
})
})
)
}, (item: number) => item.toString())
}
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
}
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值