Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Navigation View Item Color Dynamically Android

I'd like to build a navigation drawer where each item has a different selection color (the icon tint and text color) as the google play store has:

enter image description here

I'm not sure how they've solved this, I think they use different activities with different drawers. I want to use fragments and I want to change the icon tint and text color. Any ideas how I can do this? I'm using google's design support library and a drawer layout with a navigation view in there.

like image 581
vigonotion Avatar asked Jun 21 '15 18:06

vigonotion


2 Answers

use app:itemIconTint in your NavigationView for icons and use app:itemTextColor for textColors

Sample :

drawable/navigation_text_color :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This is used when the Navigation Item is checked -->
    <item android:color="#009688" android:state_checked="true" />
    <!-- This is the default text color -->
    <item android:color="#E91E63" />
</selector>

and layout :

<android.support.design.widget.NavigationView
       .
       .
       app:itemTextColor="@drawable/navigation_text_color"/>
like image 197
DJafari Avatar answered Nov 03 '22 04:11

DJafari


If by dynamically you mean programmatically you could try this:

// FOR NAVIGATION VIEW ITEM TEXT COLOR
int[][] states = new int[][]{
        new int[]{-android.R.attr.state_checked},  // unchecked
        new int[]{android.R.attr.state_checked},   // checked
        new int[]{}                                // default
};

// Fill in color corresponding to state defined in state
int[] colors = new int[]{
        Color.parseColor("#747474"),
        Color.parseColor("#007f42"),
        Color.parseColor("#747474"),
};

ColorStateList navigationViewColorStateList = new ColorStateList(states, colors);

// apply to text color
navigationView.setItemTextColor(navigationViewColorStateList);

// apply to icon color
navigationView.setItemIconTintList(navigationViewColorStateList);

So you could define multiple colors for different settings like Day or Night.

like image 7
Robert Avatar answered Nov 03 '22 05:11

Robert