当 showAsAction="never" 时向菜单项添加图标

Add icons to menu items when showAsAction="never"

我在菜单中有项目,这是其中之一

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:id="@+id/settings"
    android:title="Settings"
    app:showAsAction="never"
    android:icon="@drawable/icon"/>

我的菜单是这样的...

但我希望图标像这个菜单一样显示

有人可以帮忙吗?

尝试像下面这样膨胀你的菜单项,它对我有用:

    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        if(menu instanceof MenuBuilder){
            MenuBuilder m = (MenuBuilder) menu;
            //noinspection RestrictedApi
            m.setOptionalIconsVisible(true);
        }

        return true;
    }

您有 2 个解决方案

 < item
              android:id="@+id/action_add_contact"
              android:icon="@drawable/ic_icon"
              android:title="Add contact"
              app:showAsAction="ifRoom" />

或以编程方式添加菜单项

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_patient_home_screen, menu);

        menu.add(0, 1, 1, menuIconWithText(getResources().getDrawable(R.mipmap.user_2), getResources().getString(R.string.action_profile)));
        menu.add(0, 2, 2, menuIconWithText(getResources().getDrawable(R.mipmap.add_user), getResources().getString(R.string.action_add_user)));
        menu.add(0, 3, 3, menuIconWithText(getResources().getDrawable(R.mipmap.switch_profile), getResources().getString(R.string.action_switch_profile)));
        menu.add(0, 4, 4, menuIconWithText(getResources().getDrawable(R.mipmap.logout), getResources().getString(R.string.action_sign_out)));
        return true;
    }

您必须在 onCreateOptionsMenu

中使用 MenuBuilder.setOptionalIconsVisible(true)
MenuBuilder m = (MenuBuilder) menu;
m.setOptionalIconsVisible(true);