在 Android 中检查时为以编程方式添加的导航视图菜单项设置背景颜色

Wai*_*ein 6 android menuitem navigation-drawer android-navigationview

我正在开发一个 Android 应用程序。在我的应用程序中,我以编程方式将菜单项添加到导航视图。但是我在检查时设计该项目时遇到问题。我的问题现在只有在检查项目时更改文本颜色。但想要的是我想要用如下背景突出显示的项目。

在此处输入图片说明

我正在像这样以编程方式添加菜单项

menu.add(CATEGORY_MENU_GROUP_ID, itemId, i + 1, title).setIcon(dIcon).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        item.setChecked(true);
                        return true;
                    }
                });
Run Code Online (Sandbox Code Playgroud)

我跟着这个问题Android - Navigation View item menu background color

所以我创建了这样的背景项目(nav_item_bg.xml)

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid android:color="@color/lightGray" >
    </solid>

    <!-- view border color and width -->
    <stroke
        android:width="1dp"
        android:color="@color/lightGray" >
    </stroke>

    <!-- Here is the corner radius -->

</shape>
Run Code Online (Sandbox Code Playgroud)

我的导航视图 xml

<android.support.design.widget.NavigationView
        app:itemIconTint="@drawable/drawer_item"
        app:itemTextColor="@drawable/drawer_item"
        android:id="@+id/left_nv_view"

        app:headerLayout="@layout/header_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start" />
Run Code Online (Sandbox Code Playgroud)

这是我在 drawable 中的 drawer_item.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorAccent"  android:state_enabled="true" android:state_checked="true" />
    <!--state is enabled and not checked-->
    <item android:color="@color/black" android:state_enabled="true" android:state_checked="false" />
    <!--state (menu item) is disabled -->
    <item android:state_enabled="false" android:color="@color/lightGray"  />
</selector>
Run Code Online (Sandbox Code Playgroud)

当我运行时,导航视图中所有菜单项的背景都会改变,即使它们没有被选中。我想要的只是在选择时更改。我怎样才能实现它?

我尝试将 nav_item_bg.xml 更改为此

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/lightGray"  android:state_enabled="true" android:state_checked="true" />
    <!--state is enabled and not checked-->
    <item android:color="@color/white" android:state_enabled="true" android:state_checked="false" />
    <!--state (menu item) is disabled -->
    <item android:state_enabled="false" android:color="@color/white"  />
</selector>
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

小智 4

添加新菜单后,只需为其设置 checkAble 值:

menu.add(CATEGORY_MENU_GROUP_ID, itemId, i + 1, title).setIcon(dIcon).setCheckable(true);
Run Code Online (Sandbox Code Playgroud)