文档管理中心
FAQ应用框架开发UI框架组件使用如何实现根据不同的列表项,弹出不同的上下文菜单

如何实现根据不同的列表项,弹出不同的上下文菜单

问题现象

给List组件的Item绑定上下文菜单,按条件判断是否显示上下文菜单,且需要根据列表项的不同,弹出不同的上下文菜单,该如何实现?

效果预览

背景知识

  • List:列表包含一系列相同宽度的列表项。适合连续、多行呈现同类数据,例如图片和文本。
  • bindContextMenu:给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。

解决方案

首先对List组件的Item进行判断,使偶数项有菜单弹出,奇数项则无菜单弹出。菜单弹出方式为长按弹出菜单且弹出菜单的内容也不同。

完整示例参考如下:

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct listDemo {
  4. private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  5. @State listData: number[] = [0, 0, 0];
  6. // @Builder装饰器:构建上下文菜单组件
  7. @Builder
  8. MenuBuilder(num: number, flag: boolean) {
  9. // 根据flag参数决定是否显示菜单
  10. if (flag) {
  11. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  12. ForEach(this.listData, (index:number) => {
  13. Column() {
  14. Row() {
  15. Image($r('app.media.startIcon')).width(20).height(20).margin({ right: 5 }) // 可根据具体需要引用资源
  16. Text(`Menu${num}`).fontSize(20)
  17. }
  18. .width('100%')
  19. .height(30)
  20. .justifyContent(FlexAlign.Center)
  21. .align(Alignment.Center)
  22. // 如果不是最后一个菜单项,显示分隔线
  23. if (index !== this.listData.length - 1) {
  24. Divider().height(10).width('80%').color('#ccc')
  25. }
  26. }.padding(5).height(40)
  27. });
  28. }.width(100)
  29. }
  30. };
  31. build() {
  32. Column() {
  33. List({ space: 20, initialIndex: 0 }) {
  34. ForEach(this.arr, (item: number) => {
  35. // 根据item奇偶性决定是否绑定上下文菜单
  36. if (item % 2 === 0) {
  37. ListItem() {
  38. Text('' + item)
  39. .width('100%')
  40. .height(100)
  41. .fontSize(16)
  42. .textAlign(TextAlign.Center)
  43. .borderRadius(10)
  44. .backgroundColor(0xFFFFFF) // 绑定上下文菜单,使用MenuBuilder生成菜单,长按触发
  45. .bindContextMenu(this.MenuBuilder(item, true), ResponseType.LongPress)
  46. };
  47. } else {
  48. ListItem() {
  49. Text('' + item)
  50. .width('100%')
  51. .height(100)
  52. .fontSize(16)
  53. .textAlign(TextAlign.Center)
  54. .borderRadius(10)
  55. .backgroundColor(0xFFFFFF)
  56. .bindContextMenu(this.MenuBuilder(item, false), ResponseType.LongPress)
  57. };
  58. }
  59. }, (item: string) => item)
  60. }.width('90%')
  61. .scrollBar(BarState.Off)
  62. }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
  63. }
  64. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词