Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

android - NavigationView(Change Color of Selected Item)

Is there any way to change the Item color programmatically of the selected item
in the navigation drawer?
I'am able to use the app:itemTextColor, but the problem is if i used this,
the checked in the menu item will not highlight.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="Home" />
        <item
            android:id="@+id/nav_search"
            android:icon="@drawable/ic_search_black"
            android:title="Search Location" />
        <item
            android:id="@+id/nav_fav"
            android:icon="@drawable/ic_favorite"
            android:title="Favorites" />
        <item
            android:id="@+id/nav_route"
            android:icon="@drawable/ic_place"
            android:title="Route" />

        <item
            android:id="@+id/nav_recent"
            android:icon="@drawable/ic_nav_route"
            android:title="Recent Location" />
    </group>

    <item android:title="Others">
        <menu>
            <item
                android:id="@+id/nav_settings"
                android:checked="true"
                android:checkable="true"
                android:icon="@drawable/ic_settings"
                android:title="Settings" />
            <item
                android:id="@+id/nav_about"
                android:icon="@android:drawable/ic_menu_send"
                android:title="About" />
        </menu>
    </item>
</menu>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

create a selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/primary" android:state_checked="true" />
        <item android:drawable="@android:color/transparent" />
</selector>

and set

app:itemBackground="@drawable/nav_view_item_background"

then the selected item will be highlighted.

if you want to change the text color then set

app:itemTextColor="@drawable/nav_view_item_textcolor"

and create a selector for it like

<selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:color="@android:color/white" android:state_checked="true" />
     <item android:color="@color/primary" />
</selector>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...