What does onPrepareOptionsMenu do?

淺唱寂寞╮ 提交于 2019-11-29 10:43:30

问题


I want to make Option Menu for Android, I have visit this site. In their script, I found onPrepareOptionsMenu, I try to compile and run using Android 2.3.3 compiler with and without onPrepareOptionsMenu, both works, but I didn't see any difference.

public boolean onCreateOptionsMenu(Menu menu){
//code here
}

public boolean onOptionsItemSelected(MenuItem item){
//code here
}

public boolean onPrepareOptionsMenu(Menu menu){
//code here
}

What is actually onPrepareOptionsMenu method do? Is that method important? Could I just delete the method?


Addition

Oh, I also hear about Action Bar in Android 3.0, it says that Action Bar is the alternative way for make Option Menu, and it using onPrepareOptionsMenu. Is that right?

Thank you...


回答1:


Take a look in the API:

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.




回答2:


If you want to alter the menu before it's shown to the user, you can put code to do that into onPrepareOptionsMenu. I've used that dynamically to disable some menu options in some circumstances.

As an example of when one might want to disable a menu option, I had an app where there was a way of specifying a destination. One of my menu options was to calculate a route to the destination. However, if a destination wasn't specified, that option didn't apply, so I used onPrepareOptionsMenu to disable that menu option when it wasn't applicable.

From Android 3.0 and beyond, there's the ActionBar, which is a menu bar. The most important items go into the ActionBar itself, but then there's an overflow for when there's not enough room on the action bar. One can specify that menu items should always be in the overflow menu and never on the action bar itself. On some devices, the action bar overflow corresponds to the permanent menu button on the device, whereas on other devices which don't have a menu button the overflow menu is seen on the right hand side of the action bar as three vertical dots.




回答3:


onCreateOptionsMenu is called once, when your activity is first created. If it returns false, no option menu is shown and onPrepareOptionsMenu is never called.

If onCreateOptionsMenu returns true, onPrepareOptionsMenu is also called before the activity is displayed, and also every time the options menu is invalidated. Use onPrepareOptionsMenu if you need to enable/disable, show/hide, or add/remove items after creating it.

If your menu does not change, use onCreateOptionsMenu.



来源:https://stackoverflow.com/questions/16758517/what-does-onprepareoptionsmenu-do

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