DEV Community

HarmonyOS
HarmonyOS

Posted on

Grid Item Drag and Move with Auto-Scroll Functionality

Read the original article:Grid Item Drag and Move with Auto-Scroll Functionality

Context

When implementing drag-and-drop functionality for grid items, developers may encounter limitations where items can only be exchanged within the visible range, and attempting to implement custom scrolling logic can cause display abnormalities.

Description

The issue involves two main scenarios when implementing grid item reordering:

  1. Limited Exchange Range: Items can only be repositioned within the currently visible area of the grid
  2. Manual Scroll Implementation Issues: Custom sliding logic implementation can lead to visual abnormalities and unstable behavior

These limitations prevent smooth user experience when trying to move items to positions outside the current viewport.

Solution

Use the onMove attribute which provides built-in support for both scrolling and component swapping animations. This approach eliminates the need for manual scroll implementation and handles edge cases automatically.

Example Code

@Entry
@Component
struct ForEachSort {
  @State arr: Array<string> = [];

  build() {
    Row() {
      List() {
        ForEach(this.arr, (item: string) => {
          ListItem() {
            Text(item.toString())
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .size({height: 100, width: "100%"})
          }
          .margin(10)
          .borderRadius(10)
          .backgroundColor("#FFFFFFFF")
        }, (item: string) => item)
        .onMove((from: number, to: number) => {
          let tmp = this.arr.splice(from, 1);
          this.arr.splice(to, 0, tmp[0]);
        })
      }
      .width('100%')
      .height('100%')
      .backgroundColor("#FFDCDCDC")
    }
  }

  aboutToAppear(): void {
    for (let i = 0; i < 30; i++) {
      this.arr.push(i.toString());
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Key Features of onMove

  • Automatic Scrolling: Handles viewport scrolling when dragging items to edges
  • Built-in Animations: Provides smooth transition animations during item swapping
  • Edge Case Handling: Manages boundary conditions and prevents display abnormalities
  • Simple Implementation: Requires minimal code compared to custom scroll logic

Key Takeaways

  • Use the native onMove attribute instead of implementing custom drag-and-scroll logic
  • The onMove callback receives from and to parameters for easy array manipulation
  • Built-in scrolling and animations eliminate common edge case issues
  • This approach works reliably across different screen sizes and content lengths
  • Avoid manual scroll implementation as it can cause visual abnormalities and unstable behavior

Written by Emincan Ozcan

Top comments (0)