文档管理中心

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

问题现象

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

背景知识

解决方案

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

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct GestureGroupDemo {
  4. @State isMenu: boolean = false;
  5. @State isPopup: boolean = false;
  6. @Builder
  7. bindMenuBuilder() {
  8. Row() {
  9. Text('MenuContent');
  10. }.backgroundColor(Color.Pink);
  11. }
  12. @Builder
  13. bindPopupBuilder() {
  14. Row() {
  15. Text('PopupContent');
  16. }.backgroundColor(Color.Orange);
  17. }
  18. build() {
  19. RelativeContainer() {
  20. Button('长按或者点击')
  21. .alignRules({
  22. center: { anchor: '__container__', align: VerticalAlign.Center },
  23. middle: { anchor: '__container__', align: HorizontalAlign.Center }
  24. })
  25. .fontSize(28)
  26. .gesture(
  27. GestureGroup(GestureMode.Exclusive,
  28. LongPressGesture({ repeat: true })
  29. .onAction(() => {
  30. this.isPopup = false;
  31. this.isMenu = true;
  32. }),
  33. TapGesture({ count: 1, fingers: 1 })
  34. .onAction(() => {
  35. this.isMenu = false;
  36. this.isPopup = !this.isPopup;
  37. }))
  38. )
  39. .bindContextMenu(this.isMenu, this.bindMenuBuilder())
  40. .bindPopup(this.isPopup, {
  41. builder: this.bindPopupBuilder(), onStateChange: (e) => {
  42. if (!e.isVisible) {
  43. this.isPopup = false;
  44. }
  45. },
  46. });
  47. }
  48. .width('100%')
  49. .height('100%');
  50. }
  51. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词