DEV Community

HarmonyOS
HarmonyOS

Posted on

Horizontal Looping WaterFlow with ArkUI

Read the original article:Horizontal Looping WaterFlow with ArkUI

Requirement Description

The developer needs to implement a horizontally scrollable, cyclic WaterFlow layout in ArkUI, similar to how it's done on Android using StaggeredGridLayoutManager and RecyclerView.

Background Knowledge

ArkUI provides the WaterFlow component for displaying staggered grid layouts. By default, it scrolls vertically. To enable horizontal scrolling, additional configuration is needed, and loop-like behavior (infinite scroll) must be simulated manually.

Implementation Steps

  1. Set the layout direction of WaterFlow to FlexDirection.Row for horizontal scrolling.
  2. Define a template with multiple rows and columns to simulate grid behavior.
  3. Set the height of FlowItem and image content to 100% to fill each cell.
  4. Load image assets using a naming pattern with modulo operation for pseudo-looping.
  5. Handle the onReachEnd event to dynamically add more items to the data source.

Code Snippet / Configuration

WaterFlow({ items: this.dataSource }) {
  FlowItem((item) => {
    Column() {
      Text("N" + item).fontSize(12).height('16')
      Image('res/waterFlowTest(' + item % 5 + ').jpg')
        .objectFit(ImageFit.Fill)
        .height('100%')
        .layoutWeight(1)
    }
    .width(this.itemWidthArray[item % 100])
    .height('100%')
  })
}
.layoutDirection(FlexDirection.Row)
.columnsTemplate("1fr 1fr 1fr")
.rowsTemplate("1fr 1fr")
.onReachEnd(() => {
  console.info("onReachEnd")
  for (let i = 0; i < 100; i++) {
    this.dataSource.addLastItem();
  }
})
Enter fullscreen mode Exit fullscreen mode

Test Results

The implementation was confirmed to work and accepted by the developer as the correct solution.

Limitations or Considerations

ArkUI WaterFlow does not support native loop attributes like Swiper. Therefore, developers must simulate looping manually by managing the data source and modulo logic.

Written by Arif Emre Ankara

Top comments (0)