简体   繁体   中英

Android: Change color of navigationView selected item programatically

I created a drawer with a navigation view. In an other part of the activity, I have a button. When I click on this button, I want the selected item of the navigation view to change its color. Do you know how to do that?

Edit: For now I tried this:

private void changeNavigationColor(int resColor){
    int[][] state = new int[][] {
            new int[] {android.R.attr.state_checked} // unchecked
    };
    int[] color = new int[] {
            getResources().getColor(resColor)
    };
    ColorStateList colorStateList= new ColorStateList(state, color);
    navigationView.setItemTextColor(colorStateList.getColorForState());
    navigationView.setItemIconTintList(colorStateList);
}

But it is changing the whole colorListState whereas I just want to change it the check state

Do this :

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header_dashboard"
        app:itemIconTint="@drawable/drawer_item"  // add this 
        app:itemTextColor="@drawable/drawer_item" // add this
        app:menu="@menu/activity_dashboard_drawer" />

drawer_item.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="AFTER_CLICK_CHANGE_COLOR_TEXT" android:state_checked="true" />
    <item android:color="NAVIGATION_DRAWER_TEXT_COLOR" />
</selector>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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