简体   繁体   English

如何动态更改bottomAppBar菜单图标

[英]How to change dynamically bottomAppBar menu icon

In my application I want to use com.google.android.material.bottomappbar.BottomAppBar view. 在我的应用程序中,我想使用com.google.android.material.bottomappbar.BottomAppBar视图。
I want show some menu items into this view and for this I write this code : detailBottomAppBar.replaceMenu(R.menu.empty_menu); 我想在此视图中显示一些菜单项,为此,我编写以下代码: 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 . 但是我不想 用click来改变这个项目, 我想在没有click listener的情况下进行开放 activity来改变图标。

How can I solve this? 我该如何解决?

You can save the Menu variable when you're creating the menu. 创建菜单时,可以保存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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM