Do I need an empty onCreateOptionsMenu for empty menus? - android

In my app I have some activities without menu items, that use the following override:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.appbar_menu_empty, menu);
return true;
}
This works good. If I remove the override, I get the same effect on Android 5.1, i.e. an action bar with no icons.
So the question is: can I drop the override?
The documentation of Activity.onCreateOptionsMenu states:
The default implementation populates the menu with standard system menu items.
What does that mean? Do I need to expect that Android comes up with some buttons I did not explicitly add?

You can remove OncreateOptionsMenu() if you dont want to have menu items.
If you want to add menu items, edit the menu.xml file in resources/menu directory.

From the docs the method is defined in Activity class as below
Initialize the contents of the Activity's standard options menu. You
should place your menu items in to menu.
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(android.view.Menu).
The default implementation populates the menu with standard system
menu items. These are placed in the android.view.Menu.CATEGORY_SYSTEM
group so that they will be correctly ordered with application-defined
menu items. Deriving classes should always call through to the base
implementation.
You can safely hold on to menu (and any items created from it), making
modifications to it as desired, until the next time
onCreateOptionsMenu() is called.
When you add items to the menu, you can implement the Activity's
onOptionsItemSelected(android.view.MenuItem) method to handle them
there.
Parameters:
menu The options menu in which you place your items. Returns:
You must return true for the menu to be displayed; if you return false it will not be shown.
public boolean onCreateOptionsMenu(Menu menu) {
if (mParent != null) {
return mParent.onCreateOptionsMenu(menu);
}
return true;
}
also check this SO thread out onCreateOptionsMenu() calling super
check the code for Activity class here http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Activity.java#Activity.onCreateOptionsMenu%28android.view.Menu%29

see some sample code here where you need to show option in action bar menu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_act_add_recipe, menu);
super.onCreateOptionsMenu(menu, inflater);
}
/res/menu/menu_act_add_recipe.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_add_image"
android:icon="#drawable/ic_tab_add_image_white"
android:orderInCategory="100"
android:title="#string/action_preview"
app:showAsAction="always" />
<item
android:id="#+id/action_recipe_preview"
android:icon="#drawable/ic_tab_check_white"
android:orderInCategory="100"
android:title="#string/action_preview"
app:showAsAction="always" />

Related

Showing Menu in one of the fragments of View Pager

I am having Viewpager with 3 fragments. I want to show menu in only one of the fragments.
1st, I don't know why toolbar.inflateMenu doesn't work.
2nd, the menu works, if I have onPrepareOptionsMenu method and do
getMenuInflater().inflate(R.menu.add_user, menu); but the menu is displayed in all the fragments.
So, according to other questions in stack overflow, I implemented the below code, but it doesn't show the menu, it enters the method but menu is not shown.
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
//getMenuInflater().inflate(R.menu.add_user, menu);
info("Menu=>${tabs_viewpager.currentItem}")
val menuItem = menu?.findItem(R.id.addUserMenu)
menuItem?.setVisible(tabs_viewpager.currentItem == 1)
return true
}
The control comes to this method and shows currentItem. But it doesn't display the menu. Menu is there with id. Can someone direct me what can I correct to get this work?
try calling setHasOptionsMenu(true); in oncreate() of the fragments where you want the menu to show (you can set it to false in the fragments where you do not want the menu to show).
also include:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// your code
}
in the fragments where you want to set/change the menu. this is called everytime before the menu is shown.
you can also call invalidateOptionsMenu() or supportInvalidateOptionsMenu() (if you're using the support library) to force onPrepareOptionsMenu(menu) to be called.
you may want to check out this menus tutorial
good luck
clive

Replace action bar menu through two menu

I want replace current menu of action bar with another when change action bar.
To achieve this I wrote:
getMenuInflater().inflate(R.menu.menu2, menu_bar);
But it add new menu at the rest of current menu.
What i want is remove current and add the new one.
How can I do that?
You can call invalidateOptionsMenu(), which will cause the system to call onPrepareOptionsMenu(Menu menu) again. Inside this method, just check which one of your two menus you should inflate, after calling menu.clear().
Note that invalidateOptionsMenu() has been introduced in API 11 (Honeycomb). If you need to target a lower API level, you can store your Menu object from onPrepareOptionsMenu(Menu menu) as an attribute in your Activity, and directly call clear() on it, then inflate the needed menu as you are already doing.
If you're doing it when changing fragments then:
(1) Create a menu file for fragment
(2) onCreate() method of Fragment set setHasOptionsMenu(true);
(3) Override onCreateOptionsMenu, where you'll inflate the fragment's menu and attach it to your standard menu.
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu2, menu);
}
(4) Override onOptionItemSelected in your fragment for item handlers.
Check the link below for more details..
the answer below is correct just has a extra point that will said
You can call invalidateOptionsMenu(), which will cause the system to call onPrepareOptionsMenu(Menu menu) again. Inside this method, just check which one of your two menus you should inflate, after calling menu.clear().
Note that invalidateOptionsMenu() has been introduced in API 11 (Honeycomb). If you need to target a lower API level, you can store your Menu object from onPrepareOptionsMenu(Menu menu) as an attribute in your Activity, and directly call clear() on it, then inflate the needed menu as you are already doing.
point : at onPrepareOptionsMenu(Menu menu) should not call older menu item that lead to Error
public boolean onPrepareOptionsMenu(Menu menu) {
// Error -> menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
menu.clear();
getMenuInflater().inflate(current_menu, menu);
return super.onPrepareOptionsMenu(menu);
}

Android Optionsmenu does not change

So my problem is, is that I have a fragment. This fragment is used for creating new objects and editing existing objects.
When I create a new objects, I want to have a save button. And when I edit an object I also want a delete button.
I have two menu layout files. Which are
R.menu.element_actionbar_edit
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_delete"
android:icon="#drawable/ic_action_delete"
android:title="#string/delete"
yourapp:showAsAction="always"/>
<item android:id="#+id/action_save"
android:icon="#drawable/ic_action_done"
android:title="#string/save"
yourapp:showAsAction="always"/>
</menu>
R.menu.element_actionbar_add
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_save"
android:icon="#drawable/ic_action_done"
android:title="#string/save"
yourapp:showAsAction="always"/>
</menu>
Whenever the fragment with all the actions is called, it only onCreateOptionsMenu.
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.element_actionbar_add, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Eventhough I call the R.menu.add layout it still adds two items to the actionbar, before it actually inflates the menu already contains two items.
This fragment is the only place where I actually use a menu right now.
First I had added an if statement in the options create, to check if there was passed an existing object to edit, but in this case it did show the correct layout, but when nothing is passed I should get only the save button?Why does it show the wrong layout, without even specifying it anywhere else?
EDIT:
So it worked!
#Override
public void onPrepareOptionsMenu(Menu menu) {
if(currentObject==null) {
Global.ACTIVITY.getMenuInflater().inflate(R.menu.element_actionbar_add, menu);
}else{
Global.ACTIVITY.getMenuInflater().inflate(R.menu.element_actionbar_edit,menu);
}
super.onPrepareOptionsMenu(menu);
}
At first setting the menu using the onPrepare didn't work either. I had to delete the app from my phone completely, and reinstall it to make it work.
If you want your menus to change dynamically you should not
use onCreateOptionMenu instead use onPrepareOptionMenus
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(save){
menu.add(0, ADD, 0, "Save");
}
else{
// add rest
}
return super.onPrepareOptionsMenu(menu);
}
this method is called each time you click your menu button and menu.clear() is must since each time you add a menu.
Kindly share your results after implementing.

Android - Correct use of invalidateOptionsMenu()

I have been searching a lot on invalidateOptionsMenu() and I know what it does. But I cannot think of any real life example where this method could be useful.
I mean, for instance, let's say we want to add a new MenuItem to our ActionBar, we can simply get the Menu from onCreateOptionsMenu(Menu menu) and use it in any button's action.
Now to my real question, is following the only way of using invalidateOptionsMenu()?
bool _OtherMenu;
protected override void OnCreate (Bundle bundle)
{
_OtherMenu = false;
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate
{
if(_OtherMenu)
_OtherMenu = false;
else
_OtherMenu = true;
InvalidateOptionsMenu ();
};
}
public override bool OnCreateOptionsMenu (IMenu menu)
{
var inflater = this.SupportMenuInflater;
if(_OtherMenu)
inflater.Inflate (Resource.Menu.another_menu, menu);
else
inflater.Inflate (Resource.Menu.main_activity_menu, menu);
return base.OnCreateOptionsMenu (menu);
}
Click the button and a different menu appears. Click the button again and previous menu appears.
P.S. Sorry for the C# syntax.
invalidateOptionsMenu() is used to say Android, that contents of menu have changed, and menu should be redrawn. For example, you click a button which adds another menu item at runtime, or hides menu items group. In this case you should call invalidateOptionsMenu(), so that the system could redraw it on UI. This method is a signal for OS to call onPrepareOptionsMenu(), where you implement necessary menu manipulations.
Furthermore, OnCreateOptionsMenu() is called only once during activity (fragment) creation, thus runtime menu changes cannot be handled by this method.
All can be found in documentation:
After the system calls onCreateOptionsMenu(), it retains an instance
of the Menu you populate and will not call onCreateOptionsMenu() again
unless the menu is invalidated for some reason. However, 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 an onPrepareOptionsMenu()
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().
use this to reload new menu during app lifecycle:
new:
getActivity().invalidateOptionsMenu();
old
ActivityCompat.invalidateOptionsMenu(getActivity());
You need to override method onPrepareOptionsMenu(), write your update code of action menu in same method and if you are using fragment then add setHasOptionsMenu(true); in onCreateView().
Hope it helps you
One use I've found is forcing an order of operations between onResume and onCreateOptionsMenu/onPrepareOptionsMenu. The natural order (as of platform 22 at least) seems to flip flop around, especially when re-orientating your device.
Call invalidateOptionsMenu() in onResume() and you'll guarantee that onPrepareOptionsMenu will be called after onResume (it may additionally be called before). For example, this will allow enabling a menu item based on data retrieved in onResume.
/**
* Set a hint for whether this fragment's menu should be visible. This
* is useful if you know that a fragment has been placed in your view
* hierarchy so that the user can not currently seen it, so any menu items
* it has should also not be shown.
*
* #param menuVisible The default is true, meaning the fragment's menu will
* be shown as usual. If false, the user will not see the menu.
*/
public void setMenuVisibility(boolean menuVisible) {
if (mMenuVisible != menuVisible) {
mMenuVisible = menuVisible;
if (mHasMenu && isAdded() && !isHidden()) {
mHost.onSupportInvalidateOptionsMenu();
}
}
}
XML menu sample:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_edit"
android:icon="#drawable/ic_edit"
android:title="Edit Task"
app:showAsAction="always" />
<item
android:id="#+id/action_delete"
android:icon="#drawable/ic_delete"
android:title="Delete Task"
app:showAsAction="always" />
<item
android:id="#+id/action_check"
android:icon="#drawable/ic_check"
android:title="Check Task"
app:showAsAction="always" />
<item
android:id="#+id/action_uncheck"
android:icon="#drawable/ic_undo"
android:title="Uncheck Task"
app:showAsAction="always" />
</menu>
Code inside a sample fragment:
private boolean isMenuItemChecked;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setMenuVisibility(false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
try {
menu.findItem(R.id.action_check).setVisible(!isMenuItemChecked);
menu.findItem(R.id.action_uncheck).setVisible(isMenuItemChecked);
}
catch(Exception e) {
Log.e(TAG, "onPrepareOptionsMenu error");
}
}
public void loadUi(boolean isMenuItemChecked) {
this.isMenuItemChecked = isMenuItemChecked;
setMenuVisibility(true);
}
Put the initial state of the menu in onCreateOptionsMenu(...).
Use the invalidateOptionsMenu() to force onCreateOptionsMenu(...) and onPrepareOptionsMenu(...).
In onPrepareOptionsMenu(...), call menu.clear() to remove all items from the menu.
Still in onPrepareOptionsMenu(...) place your dynamic menu changes after the clear.
Edit: Here is a better answer to the question.
A good use for invalidateOptionsMenu() is when we have a ListView and Delete All MenuItem so when the ListView is empty we should use invalidateOptionsMenu() to remove the Delete All MenuItem.
Here is a question related to this answer: Question.
It's old, but hope this helps some one out in the future.
One use I found on real life scenario:
Assume you've a list of items that are stored into database, and you've 2 activities:
DisplayActivity: which displayed these objects after getting them
from database.
EditActivity: used to edit an existing item & save that into database.
You decided to have a couple of options to go from DisplayActivity to EditActivity:
First: To add a brand-new item into database.
Second: To edit an existing item.
In order not to repeat yourself by duplicating code, you decided to use EditActivity for both purposes.
And so, you want to customize Options Menu according to each purpose. For this case you'd build a default options menu using onCreateOptionsMenu(), and leave it as-is when it's time to edit an existing item; and invalidateOptionsMenu() it when it's time to create new items; and in this case onPrepareOptionsMenu() is auto triggered for customizing your menu.
For instance the Options menu can have a delete option for editing an existing item, and this should be hidden when adding a new item.
From fragment call getActivity().invalidateOptionsMenu();.

Refresh actionbar item icon

This works just fine but If I'm on a different activity and I use the back button, it won't update the action bar because the activity is already created and it won't update the action bar. Already tried to use supportInvalidateOptionsMenu() on the on_create method but it didn't work.
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
Cursor cursor = messages.getMessages();
if(cursor.getCount()>0){
inflater.inflate(R.menu.actionbar1, menu);
}else{
inflater.inflate(R.menu.actionbar2, menu);
}
return super.onCreateOptionsMenu(menu);
}
As the documentation for onCreateOptionsMenu(Menu) states:
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(Menu).
So going back to an already created Activity does not trigger onCreateOptionsMenu(Menu) again.
What I suggest you to do is create just one menu containing all the menu items and selectively activate/deactivate them in onPrepareOptionsMenu(Menu) based on one or more flags. Then put invalidateOptionsMenu() in onResume() which is called every time the Activity is shown.
Hope it helps
Try calling invalidateOptionsMenu whenever you need to change the icon.
It will destroy your menus and re-inflate them by calling onPrepareOptionsMenu.

Categories

Resources