I need to change my menu icon based on a condition, however when I use Menu.getItem(index).setIcon() it doesn't change my icon at all. I need help how to do that please
Menu.getItem(index).setIcon()
if (menu != null) {
if (observedCount != 0)
menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
else
menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));
Your code looks correct, but maybe you are using it just once inside onCreateOptionsMenu() and missing the calls that are necessary to update the icon as observedCount updates.
Approach 1
You can try doing the following in your activity:
First, override onPrepareOptionsMenu() and apply the changes there:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (observedCount != 0)
menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
else
menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));
return super.onPrepareOptionsMenu(menu);
}
Then, whenever you want the icon to be updated (i.e., whenever observedCount changes), just invoke:
invalidateOptionsMenu(); // From a fragment, call activity.invalidateOptionsMenu();
Approach 2
Another option is to save a reference to the menu inside onCreateOptionsMenu():
private Menu mMenu;
...
#Override
public void onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.your_menu, menu);
mMenu = menu;
}
Then, you can use that reference to set the icon:
if (observedCount != 0)
mMenu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
else
mMenu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));
That should hopefully do it!
P.S. Make sure you are getting the correct item when doing menu.getItem(2) (the item number 2 is actually the third one because the count starts at 0). To avoid getting the wrong item, it would be a good idea to set the item you want to change with an ID and then replace menu.getItem(2) with menu.findItem(R.id.your_item_id).
Related
At the beginning I have two items and the 2nd gets a listener with:
final View view = findViewById(R.id.list_item);
if (view != null) {
view.setOnLongClickListener(v -> {
Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show();
return true;
});
}
}
But if I add a new item with menu.add("name"); the listener is on the newly added item and not on the old one (list_item)
I have already tested many other alternatives, but they don't work!
I just need help on how to keep the item ID or how the listener stays on the item.
When you add an item using ``menu.add(...)` it returns a reference to the newly added item. You can set the listener like this:
final MenuItem newItem = menu.add("New item");
newItem.setOnMenuItemClickListener(menuItem -> {
// Handle your click here!
return true;
});
However, you should add/remove menu items by overriding onPrepareOptionsMenu(Menu menu). When you use menu.add(...) use the overload that allows you to set the itemId:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 314159, Menu.NONE, "New item");
return super.onPrepareOptionsMenu(menu);
}
Note that the above will be called each time the menu is going to be shown (very convenient).
Then you can handle the menu being selected from onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 314159) {
// Handle menu selection here!
}
return super.onOptionsItemSelected(item);
}
Check the AppBar/Menu guide here: https://developer.android.com/training/appbar
How can I add menu items to the menu of the DrawerLayout in Java and set onOptionsItemSelected to it. (I don't know how many items are needed; the user adds them)
I have an arraylist of custom objects that have a title that I want to display in the menu and when clicked on the item I want to change what is being displayed in the main Activity, by passing which one of the objects was clicked on.
I know that it is possible to add a menu item like this, but the problem is that I don't know how many there are going to be, so setting the onOptionsItemSelected to the right amount of items is what I am looking for
private static final int MENU_ITEM_ITEM1 = 1;
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MENU_ITEM_ITEM1, Menu.NONE, "Item name");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_ITEM1:
return true;
default:
return false;
}
}
Thanks for your help!
EDIT:
I see how how this might seem like a duplicate question, but the other questions and answers did not help. I am looking for a way to set onOptionsItemSelected to an unknown amount of items (the size of an ArrayList) and then display the selected Object in the main Activity
Thanks
I am using Google My Tracks code from here in my app.
Although in the app itselfthe menu bar is visible. when I integrate it in my app I cannot see the menu bar.
The code is exactly the same.
In the following code I cannot see the system.out.println message.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
System.out.println("Menu created");
getMenuInflater().inflate(R.menu.track_list, menu);
menu.findItem(R.id.track_list_feedback)
.setVisible(ApiAdapterFactory.getApiAdapter().isGoogleFeedbackAvailable());
searchMenuItem = menu.findItem(R.id.track_list_search);
ApiAdapterFactory.getApiAdapter().configureSearchWidget(this, searchMenuItem, trackController);
startGpsMenuItem = menu.findItem(R.id.track_list_start_gps);
refreshMenuItem = menu.findItem(R.id.track_list_refresh);
exportAllMenuItem = menu.findItem(R.id.track_list_export_all);
importAllMenuItem = menu.findItem(R.id.track_list_import_all);
deleteAllMenuItem = menu.findItem(R.id.track_list_delete_all);
return true;
}
If it makes any difference, in all my other activities except the ones imported from this project, I do not use the menu bar.
If this code resides inside a Fragment, make sure you call setHasOptionsMenu(true) in onCreate() method of this Fragment.
When I touch this "Edit" button I want it to change to "Done". Is there a way to do this?
I tried this but it only works when opening the menu on the right side:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// change the text here.
return super.onPrepareOptionsMenu(menu);
}
I assume that, at some point, you inflate the menu, yes?
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.some_menu_layout, menu);
return true;
}
So you can go into your menu (in this case, res/menu/some_menu_layout.xml), and find the android:id of the menu item you want to find. You should then be able to use menu.findItem(theId).setTitle("Done");. (You may have to save your Menu variable as a local member to do this.)
Okay, when my app starts it has two tabs, and one action in the action bar, when I switch to the second tab, i change the layout, and I want to remove the action I have in the bar, and add a different one, any easy way to accomplish this?
I got it working!
All you have to do is add conditional statements to your onCreateOptionsMenu, and then simply invalidate the menu when you switch the tab! Hope this helps someone!
Conditional:
public boolean onCreateOptionsMenu(Menu menu) {
if (getSupportActionBar().getSelectedNavigationIndex() == 1) {
menu.add("Share")
.setIcon(android.R.drawable.ic_menu_share)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
if (getSupportActionBar().getSelectedNavigationIndex() == 0)) {
menu.add("Settings")
.setIcon(android.R.drawable.ic_menu_manage)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
return true;
}
And to invalidate:
invalidateOptionsMenu();
I presume your tabs are Fragments within a FragmentActivity. In that case, you should setHasOptionsMenu(true) in tab fragments' onCreate() methods. And override onCreateOptionsMenu and onOptionsItemSelected of the fragments.
The rest will be done for you (like invalidating actionItems after switching tabs etc.)