Search code examples
androidnavigation-drawersubmenu

how to make sub-menu in drawer navigation marked when it's clicked?


I have made a navigation drawer using this drawer_menu.xml, the codes are :

<?xml version="1.0" encoding="utf-8"?>
    <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/home"
            android:icon="@drawable/ic_home"
            android:title="Home"></item>
        <item
            android:id="@+id/profile"
            android:icon="@drawable/ic_profil"
            android:title="Profile"></item>
    </group>
    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/message"
                android:icon="@drawable/ic_message"
                android:title="Message"></item>
            <item
                android:id="@+id/share"
                android:icon="@drawable/ic_share"
                android:title="Share"></item>
        </menu>
    </item>
</menu>

However, when I clicked the message menu item which is in sub-category, it's not marked instead it's only marked the item which isn't in sub-category. like the following :

click to see the image

I would be glad if someone could help this :) thank you.


Solution

  • As you have , 3 items with 3rd items(communicate) will have sub items , so you need to add <group android:checkableBehavior="single"> under that sub-item ,also you have close your tag with 2 items only(home,profile) ,you didn't include 3rd item .try closing it at end ,like i have done in below code :

     <group android:checkableBehavior="single">
            <item
                android:id="@+id/home"
                android:icon="@drawable/ic_home"
                android:title="Home"></item>
            <item
                android:id="@+id/profile"
                android:icon="@drawable/ic_profil"
                android:title="Profile"></item>
    
    
    <item android:title="Communicate">
            <menu>
                  <group android:checkableBehavior="single">//selecting one item from group
                <item
                    android:id="@+id/message"
                    android:icon="@drawable/ic_message"
                    android:title="Message"></item>
                <item
                    android:id="@+id/share"
                    android:icon="@drawable/ic_share"
                    android:title="Share"></item>
                  </group>
            </menu>
        </item>
    </group>//add this