How to add a collapsible menu item inside navigation drawer in android?

Viewed 38623

I have a DrawerLayout enclosing a NavigationView and this layout activity serves as a common Navigation drawer for all the activities in my app. I am providing the menu resource for app:menu in navigation view. I have some menu items, but I want one menu item to be collapsible/expandable, so that when I click on it, it expands to show two submenus and collapses again on a second click.

I have added submenus by adding another <menu> inside the <item> but cant make it collapsible/expandable.

Additionally, I don't want to use ExpandableListView for my purpose. Instead, I just need to do some tweaks in menu resource file. Please just point me in the correct direction. I have searched Google only to find code, blogs, and examples for collapsible list items using ExpandableListView, but I need it to work with the NavigationView design widget from the design support Library.

Here's my code for the menu file:

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

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_aboutus"
        android:title="About Us" />

    <item
        android:id="@+id/nav_faq"
        android:title="FAQs" />
    <item
        android:id="@+id/nav_share"
        android:title="Share" />
    <item
        android:id="@+id/nav_myaccount"
        android:title="My Account" />
    <item
        android:id="@+id/nav_legal"
        android:title="Legal" >
        <menu>
                <item
                    android:id="@+id/nav_tnc"
                    android:title="Terms and Conditions" />
                <item
                    android:id="@+id/nav_pp"
                    android:title="Privacy Policy" />
            </group>
        </menu>
    </item>

</menu>

I want Legal menu item to be expandable having two submenu items 'Terms and Conditions', 'Privacy Policy'.

4 Answers

In addition to answers of @Stoyan Mihaylov and @arslan , do not implement visibility right in onNavigationItemSelected()! Menu will not refresh. Do it with delay, for example:

if (id == R.id.nav_settingsMenu) {
            //expandable submenu
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Menu will refresh if toggled with delay
                    boolean b=!navigationView.getMenu().findItem(R.id.nav_1).isVisible();
                    navigationView.getMenu().findItem(R.id.nav_1).setVisible(b); //to keep state
                    navigationView.getMenu().setGroupVisible(R.id.nav_settingSubmenu,b);
                }
            },50);
            return true;
        }
Related