When and how often is the onPrepareOptionsMenu() method called for ActionBar?

我只是一个虾纸丫 提交于 2019-12-17 22:57:54

问题


It is clear for Activities - the method is being called right before the menu is shown. But what about ActionBar when it is always shown? How to trigger it to be invoked to dynamically update menuItems?


回答1:


Use invalidateOptionsMenu() to trigger onPrepareOptionMenu() method as suggested by document.

On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.




回答2:


Note if your min sdk version is less than Honeycomb (aka Android 3.0 aka api level 11), and you are using ActionBarActivity you can call supportInvalidateOptionsMenu() which is the Support library version of invalidateOptionsMenu().

If your menu changes based upon an incoming intent into onCreate(), you can just do the updates in the onPrepareOptionMenu(), if you dynamically change the menu later in the activities life-cycle you will have to call invalideOptionsMenu, or supportInvalidateOptionsMenu depending on your min and target sdk versions.



来源:https://stackoverflow.com/questions/7659354/when-and-how-often-is-the-onprepareoptionsmenu-method-called-for-actionbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!