Reputation: 583
I have a function which updates the menu. The problem is: this function should be called when application starts but in onCreate()
it isn't possible because the menu wasn't create at this time so I get an exception.
Is there any other possibility to call this MenuUpdate nearly at the start?
Upvotes: 1
Views: 363
Reputation: 5020
Android activity has a method onPrepareOptionsMenu(Menu menu)
in which you can access menu items. To initiate call to this function you must call invalidateOptionsMenu()
. So the code to update menu in the activity's onCreate(...)
method will look like:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMenu();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
// Do update staff with menu instance
}
private void updateMenu() {
invalidateOptionsMenu();
}
Upvotes: 0
Reputation: 16164
If your function needs to update menu, call
supportInvalidateOptionsMenu();
in your activity class to refresh immediately.
Upvotes: 0
Reputation: 17976
You can use the function onCreateOptionsMenu
, here is an example where some menu items are hidden during the creation:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity, (android.view.Menu) menu);
this.menu = menu;
showOption(R.id.menu_edit);
hideOption(R.id.menu_check);
hideOption(R.id.menu_cancel);
return true;
}
Upvotes: 2