Android: When is onCreateOptionsMenu called during Activity lifecycle?
The onCreate method is called first, and before it finishes onCreateOptionsMenu is called.
That will be true on devices and apps with an official Honeycomb-style action bar. If there is no action bar, onCreateOptionsMenu()
should not get called until the user calls up the menu, typically by pressing the MENU button.
(I'm using screen size to determine this, my layout file for large screens has a View I check for after the layout is inflated)
That test will break very shortly, once Ice Cream Sandwich ships. From what I can tell, ICS phones will have action bars (though perhaps not system bars).
onCreateOptionsMenu(Menu menu) only gets called once during the lifecycle of an Activity
Yes. To do that you need to use:
public boolean onPrepareOptionsMenu (Menu menu)
That code will be executed every time before your options menu is shown.
More information here.
Why is onCreateOptionsMenu() called in each fragment using FragmentTransaction add() method?
If you call:
ft.add(R.id.container, fragmentA, "tag").addToBackStack(null).commit();
FragmentA will stay "resumed" and its menu will be "inflated". Then if you call:
ft.add(R.id.container, fragmentB, "tag").addToBackStack(null).commit();
FragmentA is still "resumed" and now FragmentB is also on state "resumed" and its menu will be also "inflated".
When you need to update a view you should use view.invalidate(), and this method will "redraw" the view.
Said so...
If your MainActivity has a menu, it will call invalidateOptionsMenu() to redraw MainActivity's menu and also draw FragmentA's menu. After adding FragmentB the toolbar needs to add its menu, so it will call invalidateOptionsMenu() to redraw MainActivity and FragmentA menu and also draw FragmentB's menu. That's why it's called every time you change Fragment, because the menu view needs to be redrawn.
That does not happen if you use
ft.replace(...)
because the first Fragment will be destroyed.
Hope It helps understand.
Log your MainActivity's onCreateOptionsMenu and also will be called every time you add a Fragment which has menu.
Related Topics
How to Read and Edit Android Calendar Events Using the New Android 4.0 Ice Cream Sandwich API
How to Iterate Through All Keys of Shared Preferences
Android: When Is Oncreateoptionsmenu Called During Activity Lifecycle
Android: Making a Fullscreen Application
Android: Change Default Home Application
Using Android to Submit to a Google Spreadsheet Form
Illegalstateexception: Can't Change Container Id of Fragment
How to Share Photo with Caption via Android Share Intent on Facebook
Difference Between a Clickable Imageview and Imagebutton
Command Line "Android Update Sdk" on Headless Linux
Http Status Code in Android Volley When Error.Networkresponse Is Null
Android Seekbar with Two Thumbs
How to Click or Tap on a Textview Text on Different Words
How to Display Menu Item with Icon and Text in Appcompatactivity