0

How to correctly display the selected items in the menu? via (with grey background):

enter image description here

At the moment:

enter image description here

Why without grey background?

My XML Menu:

<menu
    xmlns:android="http://schemas.android.com/apk/res/android">

    <group>

        <item
            android:id="@+id/night"
            android:icon="@drawable/ic_brightness_3_black_24dp"
            android:title="@string/navigation_view_item_1" />

        <item
            android:id="@+id/nearbyParkingPlaces"
            android:icon="@drawable/ic_local_parking_black_24dp"
            android:title="@string/navigation_view_item_2" />

        <item
            android:id="@+id/traffic"
            android:icon="@drawable/ic_traffic_black_24dp"
            android:title="@string/navigation_view_item_3" />

    </group>

    ...

</menu>

My code for NavigationItemSelectedListener:

navigation.setNavigationItemSelectedListener { menuItem ->
        drawerLayout.closeDrawers()
        when (menuItem.itemId) {
            R.id.night -> if (menuItem.isChecked) {
                menuItem.isChecked = false
                ...
            } else {
                menuItem.isChecked = true
                ...
            }
            R.id.nearbyParkingPlaces -> if (menuItem.isChecked) {
                menuItem.isChecked = false
                ...
            } else {
                menuItem.isChecked = true
                ...
            }
            R.id.traffic -> if (menuItem.isChecked) {
                menuItem.isChecked = false
                ...
            } else {
                menuItem.isChecked = true
                ...
            }
            ...
        }
        false
    }

What am I doing wrong or I missed something?


If add android:checkableBehavior="all" in <group> - selected item have grey background, but selected elements are not combine. The previous selected item is reset... I don't understand, why and how fix it?


The solution was found

  • check this related question https://stackoverflow.com/questions/30886453/change-the-color-of-a-checked-menu-item-in-a-navigation-drawer – Alleo Indong Oct 31 '17 at 15:17

1 Answers1

0

Use selector for your menu background

app:itemBackground="@drawable/activated_background.xml"

and your selector drawable will be like

<selector xmlns:android="http://schemas.android.com/apk/res/android">

            <item android:state_checked="false" android:drawable="@drawable/normal"/>

            <item android:state_checked="true"  android:drawable="@drawable/selected" />

</selector>
Vishal Pawar
  • 4,324
  • 4
  • 28
  • 54