Daniele
Daniele

Reputation: 4343

Android - Change the background color of a single item in the NavigationView

I have got the standard Android, material looking, navigation view in my app, and I was wondering if I could change the background color of just one, the first element in the list.

I tried to do it by getting the title string and setting a BackgroundColorSpan but it only changes the TextView background color.

val proItem = nav_view.menu.findItem(R.id.pro_item)
        val spanString = SpannableString(proItem.title)
        spanString.setSpan(BackgroundColorSpan(R.color.colorAccent), 0, spanString.length, 0)
        proItem.title = spanString

I was looking for something similar as the app:itemBackground tag in the NavigationView does, but it does it for every single item in the list, while I was looking to do it only on one.

Is there a way to achieve it?

Upvotes: 0

Views: 749

Answers (1)

rafa
rafa

Reputation: 1369

app:itemBackground can be used to change the background color. You can create a selector for checked state and refer the same in xml.

selector.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>

colors.xml

<color name="btn_color_green_alpha">#3300ff00</color>

layout file

<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" />

Hope this helps.

If you want only one item in selected color and don't want to apply to others, you cam make other items checkable= false.

<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>

Upvotes: 2

Related Questions