0

Is it possible to set navigation item background color dynamically

Navigation View

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:background="@color/white"
        app:itemIconTint="@color/navigation_color"
        app:itemTextColor="@color/navigation_color"
        app:itemBackground="@drawable/drawer_selector"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/activity_home_drawer"
        />

drawable_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/shape_rectangle_checked"
         android:state_checked= "true" />
     <item android:drawable="@drawable/shape_rectangle" />
</selector>

Thanks in advance

shubomb
  • 672
  • 7
  • 20
  • Possible duplicate of [Android - Navigation View item menu background color](https://stackoverflow.com/questions/31221637/android-navigation-view-item-menu-background-color) – Sunil Sunny May 30 '17 at 10:02

2 Answers2

0

In your activity simply use below code:

int customNormalColorFromServer = Color.WHITE; // Replace value with your color retreiving logic
int customFocusedColorFromServer = Color.GRAY; // Replace value with your color retreiving logic

ColorStateList colorStateList = new ColorStateList(new int[][] {
                    new int[] {android.R.attr.state_selected},
                    new int[] {-android.R.attr.state_selected}
                },
                new int[] {customFocusedColorFromServer, customNormalColorFromServer}
    );

NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(colorStateList);
phoenix
  • 496
  • 3
  • 11
  • Thanks @Mr. Rabbit, but I want to set item background color i.e, app:itemBackground="@drawable/drawer_selector" – shubomb May 30 '17 at 09:49
  • Are you getting your images from the server or just the colors? and from that colors do you want to create drawable selector or color selector? – phoenix May 30 '17 at 09:51
0

navigationView.setItemBackground(Color.parseColor("#000"));

sagar potdar
  • 598
  • 1
  • 6
  • 22