目录

实现Text长按和点击弹出不同的菜单

问题现象

Text组件绑定了bindPopup和bindMenu,想要长按显示bindMenu,点击显示bindPopup,该如何实现?

背景知识

解决方案

使用组合手势中的互斥手势GestureMode.Exclusive来实现长按手势LongPressGesture触发弹出bindMenu,点击手势TapGesture触发弹出bindPopup。

@Entry
@Component
struct GestureGroupDemo {
  @State isMenu: boolean = false;
  @State isPopup: boolean = false;

  @Builder
  bindMenuBuilder() {
    Row() {
      Text('MenuContent');
    }.backgroundColor(Color.Pink);
  }

  @Builder
  bindPopupBuilder() {
    Row() {
      Text('PopupContent');
    }.backgroundColor(Color.Orange);
  }

  build() {
    RelativeContainer() {
      Button('长按或者点击')
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .fontSize(28)
        .gesture(
          GestureGroup(GestureMode.Exclusive,
            LongPressGesture({ repeat: true })
              .onAction(() => {
                this.isPopup = false;
                this.isMenu = true;
              }),
            TapGesture({ count: 1, fingers: 1 })
              .onAction(() => {
                this.isMenu = false;
                this.isPopup = !this.isPopup;
              }))
        )
        .bindContextMenu(this.isMenu, this.bindMenuBuilder())
        .bindPopup(this.isPopup, {
          builder: this.bindPopupBuilder(), onStateChange: (e) => {
            if (!e.isVisible) {
              this.isPopup = false;
            }
          },
        });
    }
    .width('100%')
    .height('100%');
  }
}