如何在 onCreateOptionsMenu() 之后在 Android 中添加 MenuItem
我遇到了一个严重的问题。我想在用户成功登录后添加 MenuItem。
一开始我使用以下方法使其可用。
下面的代码现在不起作用,我提到它是为了说明我的想法。
Private Menu mymenu;
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
mymenu=menu;
return super.onCreateOptionsMenu(menu);
}
public void process(){
MenuInflater inflater=this.getMenuInflater();
inflater.inflate(R.menu.my_menu,mymenu);
}
看来这个想法在我记忆中有效。但是在做了一些我不记得的事情之后,它不起作用!
调试后,我发现这是因为 mymenu=null 。
我猜有一种方法可以设置 mymenu=menu
有人可以帮忙吗?
I've met a serious problem. I want to add the MenuItem after the user successfully logged in.
At the beginning I use the following method to make it available.
The following code doesn't work now , I mentioned it as to illustrate my idea.
Private Menu mymenu;
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
mymenu=menu;
return super.onCreateOptionsMenu(menu);
}
public void process(){
MenuInflater inflater=this.getMenuInflater();
inflater.inflate(R.menu.my_menu,mymenu);
}
It seems this idea worked as I remembered.But after doing something I couldn't remember , It doesn't work!
After the debug , I find it's because mymenu=null .
I guessed there is a way to set mymenu=menu
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码可能遇到的问题是调用 super 两次。
要执行您想要的操作,您可以重写 onPrepareOptionMenu 并将所有不需要的菜单项的可见性设置为隐藏,直到您的状态需要“添加”它。
只需在 onCreateOptionsMenu 中使用标准代码:
The problem you could be having with that code is calling the super twice.
To do what you want, you could override onPrepareOptionMenu and set the visibility to hidden on all menu items you don't want until your state is such that you want to "add" it.
and just use standard code in onCreateOptionsMenu:
有一个方法, onPrepareOptionsMenu(Menu menu ) 方法,您可以覆盖并动态更改菜单。
There is a method, onPrepareOptionsMenu(Menu menu) method which you could override and dynamically change the menus.