DEV Community

HarmonyOS
HarmonyOS

Posted on

how to solve the problem that the position of the dragged subcomponent will shift to both sides?

Read the original article:When dragging a subcomponent within a List component, how to solve the problem that the position of the dragged subcomponent will shift to both sides?

Question

When dragging and swapping child components within a List component, the dragged child component shifts to the left or right when the drag starts.

Short Answer

Dragging is a common action on mobile devices, often used to edit the order of items in lists and grids. ArkTS components like List and Grid provide a simple API for implementing drag effects: onItemDragStart.

You can create custom drag effects by combining gestures with GestureGroup and displaying animations with animateTo.

Applicable Scenarios

Binding the onDragStart event to implement ListItem dragging only achieves the final position change of the subcomponent, but doesn't provide a smooth transition animation during the drag process.

You can use a combination of gestures and animations to control the position change of the subcomponent during dragging, achieving a smooth drag effect.

1.Recognize combined gestures sequentially.

  • The LongPressGesture event marks the dragged element;
  • The PanGesture event records the displacement of the dragged element.
GestureGroup(GestureMode.Sequence, LongPressGesture({
    repeat: true
}).onAction((event ? : GestureEvent) => {
    // Long press to mark the dragged element
}).onActionEnd(() => {
    // End long press, remove mark
}), PanGesture({
    fingers: 1,
    direction: null,
    distance: 0
}).onActionStart(() => {
    // Start dragging, initialize movement distance
}).onActionUpdate((event: GestureEvent) => {
    // Calculate movement distance during dragging, swap the order of adjacent elements based on movement
}).onActionEnd((event: GestureEvent) => {
    // Handle drag end logic
}))
Enter fullscreen mode Exit fullscreen mode

2.During element scaling and displacement, use the display animation animateTo to control the animation effect.

// Custom animation curve
animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
    // Handle element swapping during drag
    this.offsetY += this.ITEM_INTV;
    this.dragRefOffset -= this.ITEM_INTV;
    this.itemMove(index, index - 1);
});
Enter fullscreen mode Exit fullscreen mode

Written by Hatice Akyel

Top comments (0)