HarmonyOS 5.0 应用开发——菜单的显示
作者:高心星
- 2024-10-31 江苏
本文字数:1507 字
阅读完需:约 5 分钟

【高心星出品】
菜单的显示
普通菜单的显示
bindMenu 用于显示弹出菜单。
开发方法
bindMenu(content: Array<MenuElement> | CustomBuilder, options?: MenuOptions)
复制代码
这里可以自己定义显示的菜单布局也可以使用系统默认的布局,其中 MenuElement 是负责收集菜单选项的相关信息,包含菜单项文本,icon 图标以及对应的监听事件。
效果展示:
完整代码:
import { promptAction } from '@kit.ArkUI';
@Entry@Componentstruct Menupage { @State message: string = 'Hello World'; @State datas: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
build() { Column() { List() { ForEach(this.datas, (item: string, index: number) => { ListItem() { Text('item' + item) .fontSize(20) .padding(20) .border({ width: 2, color: Color.Black }) .width('100%') .bindMenu([//菜单项信息 { value: '菜单1', action: () => {//菜单被点击事件 promptAction.showToast({ message: 'item' + item + '菜单1被点击了' }) } }, { value: '菜单2', action: () => { promptAction.showToast({ message: 'item' + item + '菜单2被点击了' }) } } ], { title: '菜单项:' })//配置菜单标题 } }) }
} .height('100%') .width('100%') }}
复制代码
上下文菜单的显示
bindContextMenu 为组件绑定弹出式菜单,通过长按或右键点击触发。
开发方法
bindContextMenu(content: CustomBuilder, responseType: ResponseType, options?: ContextMenuOptions)
复制代码
效果展示:
完整代码:
import { promptAction } from '@kit.ArkUI';
@Entry@Componentstruct ContextMenupage { @State message: string = 'Hello World'; @State datas: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 构建上下文菜单布局 @Builder gencontextmenu(item: number) { Column() { Text('保存内容').width('100%').textAlign(TextAlign.Center).padding(10) .onClick(() => { promptAction.showToast({ message: 'item' + item + '被保存了' }) }) Divider() Text('收藏内容').width('100%').textAlign(TextAlign.Center).padding(10) .onClick(() => { promptAction.showToast({ message: 'item' + item + '被收藏了' }) }) Divider() Text('分享内容').width('100%').textAlign(TextAlign.Center).padding(10) .onClick(() => { promptAction.showToast({ message: 'item' + item + '被分享了' }) }) }.width('40%') }
build() { Column() { List() { ForEach(this.datas, (item: number, index: number) => { ListItem() { Text('item' + item) .fontSize(20) .padding(20) .border({ width: 2, color: Color.Black }) .width('100%')// 绑定啥下文菜单 .bindContextMenu(this.gencontextmenu(item), ResponseType.LongPress, { placement: Placement.Bottom }) } }) } } .height('100%') .width('100%') }}
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 3
高心星
关注
天将降大任于斯人也,必先苦其心志。 2024-10-17 加入
华为开发者专家(HDE)。 10年教学经验,兼任多家科技公司技术顾问。先后从事JavaEE项目开发、Python爬虫、HarmonyOS移动应用开发等课程的教学工作。参与开发《鸿蒙应用开发基础》和《鸿蒙项目实战》等课程。









评论