android:以编程方式更改选项菜单项
是否可以通过编程方式更改选项菜单项?有人能给我举个例子吗?
另外,我想禁用某些项目,以便它们不听点击,这可能吗?
Is it possible to change the option menu items programmatically? Can anyone provide me with an example please?
Also, I want to disable certain items, so that they don't listen to the clicks, is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
对于任何需要动态更改菜单选项的人:
For anyone needs to change the options of the menu dynamically:
menu.xml
放入你的java文件中
menu.xml
put in your java file
就像尼古拉说的那样,在 onPrepareOptionsMenu() 中执行此操作。
对于操作栏中的菜单项,您必须使用以下命令使菜单无效
activity.invalidateOptionsMenu();
这里有更详细的描述 当 onPrepareOptionsMenu 切换菜单项时如何刷新 ActionBar?
Like Nikolay said do that in onPrepareOptionsMenu().
For menu items in the action bar you have to invalidate the menu with
activity.invalidateOptionsMenu();
This is descriped in more detail here How can I refresh the ActionBar when onPrepareOptionsMenu switched menu entries?
要禁用某些项目:
To disable certain items:
如果我必须更改选项菜单的内容,我会在 onMenuOpened() 期间执行它。这使我可以在用户访问菜单时检查运行状态。
If I have to change the contents of my options menu I perform it during the onMenuOpened(). This allows me to check the running state at the very moment that the user is accessing the menu.
使用我已经完成的以下几行在菜单中添加值,
尝试这项工作对我来说就像一个魅力。
using the following lines i have done to add the values in menu
try this work like a charm to me.
试试这个代码:
Try this code:
你可以像我一样做一些简单的事情。只需将文本更改为触摸菜单项时所需的内容即可。我需要关闭和打开声音,以及通过触摸来执行操作的能力。这是我的代码:
audioOn 和 touchOn 是在代码的其他部分检查的布尔值。希望这有帮助。
You can do something simple like I did. Just change the text to what is needed when the menu item is touched. I needed to turn the sound off and on, plus the ability to perform an action by touching it. Here is my code:
audioOn and touchOn are booleans checked in other parts of the code. Hope this helps.
您只需执行以下操作即可完成您的任务:
you can accomplish your task simply by implementing as below:
如果您有 BottomBar:
那么您只需调用:
In case you have a BottomBar:
Then you just need to call:
用于以编程方式访问工具栏选项菜单项的 Kotlin 代码更改文本/图标,..:
1-我们的菜单项位于菜单项文件中,例如:menu.xml,示例代码:
2-定义一个用于访问类中菜单对象的变量:
3-在 onCreateOptionsMenu 中初始化它:
4- 访问代码或 fun 中的菜单项:
Kotlin Code for accessing toolbar OptionsMenu items programmatically & change the text/icon ,..:
1-We have our menu item in menu items file like: menu.xml, sample code for this:
2- Define a variable for accessing menu object in class :
3- initial it in onCreateOptionsMenu :
4- Access the menu items inside your code or fun :