菜單控制

2024-01-22 16:18 更新

為組件綁定彈出式菜單,彈出式菜單以垂直列表形式顯示菜單項(xiàng),可通過長按、點(diǎn)擊或鼠標(biāo)右鍵觸發(fā)。

說明
  • 從API Version 7開始支持。后續(xù)版本如有新增內(nèi)容,則采用上角標(biāo)單獨(dú)標(biāo)記該內(nèi)容的起始版本。
  • CustomBuilder里不支持再使用bindMenu、bindContextMenu彈出菜單。多級菜單可使用Menu組件
  • 彈出菜單的文本內(nèi)容不支持長按選中。

屬性

名稱

參數(shù)類型

描述

bindMenu

Array<MenuItem> | CustomBuilder

給組件綁定菜單,點(diǎn)擊后彈出菜單。彈出菜單項(xiàng)支持文本和自定義兩種功能。

bindContextMenu8+

content: CustomBuilder,

responseType: ResponseType

給組件綁定菜單,觸發(fā)方式為長按或者右鍵點(diǎn)擊,彈出菜單項(xiàng)需要自定義。

MenuItem

名稱

類型

描述

value

string

菜單項(xiàng)文本。

action

() => void

點(diǎn)擊菜單項(xiàng)的事件回調(diào)。

示例

示例1

普通菜單

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MenuExample {
  5. build() {
  6. Column() {
  7. Text('click for Menu')
  8. }
  9. .width('100%')
  10. .margin({ top: 5 })
  11. .bindMenu([
  12. {
  13. value: 'Menu1',
  14. action: () => {
  15. console.info('handle Menu1 select')
  16. }
  17. },
  18. {
  19. value: 'Menu2',
  20. action: () => {
  21. console.info('handle Menu2 select')
  22. }
  23. },
  24. ])
  25. }
  26. }

示例2

自定義內(nèi)容菜單

  1. @Entry
  2. @Component
  3. struct MenuExample {
  4. @State listData: number[] = [0, 0, 0]
  5. @Builder MenuBuilder() {
  6. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  7. ForEach(this.listData, (item, index) => {
  8. Column() {
  9. Row() {
  10. Image($r("app.media.icon")).width(20).height(20).margin({ right: 5 })
  11. Text(`Menu${index + 1}`).fontSize(20)
  12. }
  13. .width('100%')
  14. .height(30)
  15. .justifyContent(FlexAlign.Center)
  16. .align(Alignment.Center)
  17. .onClick(() => {
  18. console.info(`Menu${index + 1} Clicked!`)
  19. })
  20. if (index != this.listData.length - 1) {
  21. Divider().height(10).width('80%').color('#ccc')
  22. }
  23. }.padding(5).height(40)
  24. })
  25. }.width(100)
  26. }
  27. build() {
  28. Column() {
  29. Text('click for menu')
  30. .fontSize(20)
  31. .margin({ top: 20 })
  32. .bindMenu(this.MenuBuilder)
  33. }
  34. .height('100%')
  35. .width('100%')
  36. .backgroundColor('#f0f0f0')
  37. }
  38. }

示例3

菜單(右鍵觸發(fā)顯示)

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct ContextMenuExample {
  5. @Builder MenuBuilder() {
  6. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  7. Text('Test menu item 1')
  8. .fontSize(20)
  9. .width(100)
  10. .height(50)
  11. .textAlign(TextAlign.Center)
  12. Divider().height(10)
  13. Text('Test menu item 2')
  14. .fontSize(20)
  15. .width(100)
  16. .height(50)
  17. .textAlign(TextAlign.Center)
  18. }.width(100)
  19. }
  20. build() {
  21. Column() {
  22. Text('rightclick for menu')
  23. }
  24. .width('100%')
  25. .margin({ top: 5 })
  26. .bindContextMenu(this.MenuBuilder, ResponseType.RightClick)
  27. }
  28. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號