1

In my application I want to use com.google.android.material.bottomappbar.BottomAppBar view.
I want show some menu items into this view and for this I write this code : detailBottomAppBar.replaceMenu(R.menu.empty_menu); , and with this code I can show menu items into this view.

I want to change dynamically the menu icon for one of this menu items. but I don't know how I can make it.

I can to change the icon with a click listener with below code

        detailBottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.detailMenu_favorite:
                        Toast.makeText(getViewContext(), "Favorite", Toast.LENGTH_SHORT).show();
item.setIcon(ContextCompat.getDrawable(getViewContext(), R.drawable.ic_search_24dp));
                        break;
                    case R.id.detailMenu_comment:
                        Toast.makeText(getViewContext(), "Comment", Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            }
        });

But I don't want to change this item with click, I want open activity to change the icon without the click listener .

How can I solve this?

koksalb
  • 430
  • 8
  • 14
Dear User
  • 93
  • 8
  • I'm not sure if BottomAppBar works differently from other menus, but can you show the code where you initialise the menu? Do you use `onCreateOptionsMenu`? – Ezzy Nov 08 '18 at 07:49
  • I used this methods `onCreateOptionsMenu` , `onPrepareOptionsMenu` but not work me! – Dear User Nov 08 '18 at 07:52

1 Answers1

3

You can save the Menu variable when you're creating the menu. That way you can get the specific item that you want and modify it.

private Menu _menu;

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
   getMenuInflater().inflate(R.menu.main, menu);
   _menu = menu;
}

Accessing the menu item you want

MenuItem item = _menu.findItem(R.id.menu_item_id);
item.setIcon(ContextCompat.getDrawable(getViewContext(), R.drawable.ic_search_24dp));
Ezzy
  • 1,423
  • 2
  • 15
  • 32
  • I used your code, but show me` java.lang.NullPointerException` error in `MenuItem item = _menu.findItem(R.id.detailMenu_favorite);` code. I used this code `MenuItem item = _menu.findItem(R.id.detailMenu_favorite); item.setIcon(ContextCompat.getDrawable(getViewContext(), R.drawable.ic_search_24dp));` into `onCreate` method. – Dear User Nov 08 '18 at 08:32
  • Is `_menu` null? Keep in mind that `onCreateOptionsMenu` needs to be called before you try to access `_menu`. If you're changing the icon in `onCreate`, then why not just put that icon in the menu.xml? – Ezzy Nov 08 '18 at 08:34