如何以编程方式创建 Menu 实例?即在 onCreateOptionsMenu 之外膨胀菜单 [英] How to create a Menu instance programmatically? i.e. inflate a Menu outside onCreateOptionsMenu
问题描述
我想在外部 onCreateOptionsMenu
方法(这意味着在用户不按下按钮时创建/显示菜单)膨胀一个菜单对象,所以我需要创建一个菜单实例以将其传递给 inflate 方法.
I want to inflate a menu object outside onCreateOptionsMenu
method (which means to create/show the menu when the user doesn't press the button), so I need to create a menu instance to pass it to the inflate method.
以下是我要实现的目标的示例:
Here is an example of what I am trying to achieve:
Menu menu = // How to create an instance !?
new MenuInflater(context).inflate(R.menu.my_menu, menu)
Menu 是一个接口,所以我需要知道哪个类正在实现它.我确实浏览了 Android 代码以获取有关如何创建 Menu 对象的任何提示,但仍然找不到我要查找的内容.
Menu is an interface, so I need to know which class is implementing it. I did browse Android code to get any hint on how a Menu object is created, but still could not find what I am looking for.
编辑 1
我的目标是从自定义视图中触发 onOptionsItemSelected(MenuItem item)
事件,该事件将由活动处理,因此我需要有一个带有特定 itemId 和标题的 MenuItem 对象才能传递它与事件.
My goal is to fire an onOptionsItemSelected(MenuItem item)
event from a custom view, which will be handled by the activity, so I need to have a MenuItem object with specific itemId and title to pass it with the event.
如果我能成功创建一个 Menu 对象,就很容易得到它的子 MenuItems.
If I can successfully create a Menu object, it will be easy to get its children MenuItems.
编辑 2
我不试图显示菜单,我想要的是用在菜单 XML 中定义的元素填充 ListView具有标题、图标和 itemId 并且每当单击 ListViewItem 时,我想触发在我的活动中处理的 onOptionsItemSelected(MenuItem item)
事件.
I am not trying to display a menu at all, what I want is to populate a ListView with elements defined in a menu XML that have title, icon and itemId and whenever a ListViewItem is clicked I want to fire a onOptionsItemSelected(MenuItem item)
event that is handled in my activity.
我知道我可以解析菜单 XML 以提取项目信息,但是如果不创建 标准 MenuItem 对象,我将无法触发 onOptionsItemSelected(MenuItem item)
将其作为参数传递.
I know that I can parse the menu XML to extract items information, however I will not be able to fire onOptionsItemSelected(MenuItem item)
without creating a standard MenuItem object to pass it as argument.
任何帮助将不胜感激.谢谢!
Any help will be appreciated. Thanks!
推荐答案
这里有一个获取 Menu 实例的技巧:
Here's a trick to get an instance of Menu:
PopupMenu p = new PopupMenu(getContext(), null);
Menu menu = p.getMenu();
这篇关于如何以编程方式创建 Menu 实例?即在 onCreateOptionsMenu 之外膨胀菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!