How to change dynamically bottomAppBar menu icon

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?

1 answer

  • answered 2018-11-08 08:05 Ezzy

    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));