DEV Community

HarmonyOS
HarmonyOS

Posted on

Enables the component to be extended by pressing and holding the component

Read the original article:Enables the component to be extended by pressing and holding the component

Requirement Description

In List and Grid scenarios, there are multiple list items, and a long-press preview function is desired. After long-pressing the component, a popup-like functionality should be achieved to enable a preview effect.

Background Knowledge

bindContextMenu: Binds a menu to a component. The menu’s visibility trigger can be a long press or right-click. The menu items need to be customized.

Implementation Steps

Bind a menu to the List or Grid child components and display the required information.

Code Snippet

@Entry
@Component
struct Index {
  @State arr: Array<string> = [];
  @State menu: string = 'Preview Info';

  @Builder Menu(index: number) {
    Row(){
      Text(this.menu + `${index}`)
    }
    .width('95%')
    .height(100)
    .justifyContent(FlexAlign.Center)
  }

  aboutToAppear(): void {
    for (let i = 0; i < 8; i++) {
      this.arr.push(i.toString());
    }
  }

  build() {
    Row() {
      List({ space: 8 }) {
        ForEach(this.arr, (item: string, index) => {
          ListItem() {
            Text(item.toString())
              .fontColor(Color.White)
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .size({ height: 100, width: "100%" })
          }
          .width('100%')
          .height(100)
          .borderRadius(10)
          .backgroundColor(Color.Blue)
          .bindContextMenu(this.Menu(index), ResponseType.LongPress)
        }, (item: string, index) => item + index)
      }
      .scrollBar(BarState.Off)
      .width('100%')
      .height('100%')
      .padding(15)
      .backgroundColor(Color.White)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

cke_899.gif

Limitations or Considerations

This example supports API Version 19 Release and above.

This example supports HarmonyOS 5.1.1 Release SDK and above.

This example requires DevEco Studio 5.1.1 Release and above for compilation and running.

Written by Bunyamin Akcay

Top comments (0)