到目前为止,我发现的唯一解决方法是在onCreate()返回之前手动调用invalidateOptionsMenu();那样onCreateOptionsMenu()立即被调用,我得到一个菜单,然后我终于可以添加所需的操作项.
有没有人遇到过这个问题?在onResume()之后调用onCreateOptionsMenu()时,你应该如何以编程方式设置你的动作项?
我的应用程序在JellyBean上运行,它使用内置的ActionBar(没有ActionBarSherlock),android:minSdkVersion =“14”和android:targetSdkVersion =“16”
解决方法
As a general rule,all items in the options menu (let alone action items) should have a global impact on the app,rather than affect only a small portion of the interface. […] So,even before deciding whether a menu item should appear as an action item,be sure that the item has a global scope for the current activity.
>从Menu API Guide开始:
You should never change items in the options menu based on the
View
currently in focus. When in touch mode (when the user is not using a trackball or d-pad),views cannot take focus,so you should never use focus as the basis for modifying items in the options menu. If you want to provide menu items that are context-sensitive to aView
,use a 07002.
除非您确实想要更改菜单项,否则应在onPrepareOptionsMenu()中进行更改.当发生需要更改菜单项的事件时,将相关信息放入字段并调用invalidateOptionsMenu().覆盖onPrepareOptionsMenu()并检查字段的值以确定要添加/删除的菜单项.
(它也可以调用invalidateOptionsMenu()并覆盖onCreateOptionsMenu()来修改应该显示哪些菜单项,尽管不推荐这种方法.)
更多来自Menu API Guide:
You should use
onCreateOptionsMenu()
only to create the initial
menu state and not to make changes during the activity lifecycle.
If you want to modify the options menu based on events that occur
during the activity lifecycle,you can do so in the
onPrepareOptionsMenu()
method.This method passes you the
Menu
object as it currently exists so you
can modify it,such as add,remove,or disable items. (Fragments also
provide anonPrepareOptionsMenu()
callback.)
On Android 2.3.x and lower,the system calls
onPrepareOptionsMenu()
each time the user opens the options menu (presses the Menu button).On Android 3.0 and higher,the options menu is considered to always be
open when menu items are presented in the action bar. When an event
occurs and you want to perform a menu update,you must call
invalidateOptionsMenu()
to request that the system call
onPrepareOptionsMenu()
.