app:itemBackground
可用于更改背景色。可以为选中状态创建选择器,并在XML中引用该选择器。
选择器.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- focused -->
<item android:state_checked="true" android:drawable="@color/btn_color_green_alpha"></item>
</selector>
颜色.xml
<color name="btn_color_green_alpha">#3300ff00</color>
布局文件
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemBackground="@drawable/selector" //line to be added
app:headerLayout="@layout/nav_header_main2"
app:menu="@menu/activity_main2_drawer" />
希望这有帮助。
如果您只需要一个选定颜色的项目,而不想应用于其他项目,您可以将其他项目设置为选中=假。
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_camera"
android:icon="@drawable/ic_menu_camera"
android:title="Import" />
<item
android:id="@+id/nav_gallery"
android:checkable="false" //line added here
android:icon="@drawable/ic_menu_gallery"
android:title="Gallery" />
<item
android:id="@+id/nav_slideshow"
android:icon="@drawable/ic_menu_slideshow"
android:title="Slideshow" />
<item
android:id="@+id/nav_manage"
android:icon="@drawable/ic_menu_manage"
android:title="Tools" />
</group>
</menu>