Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Android MenuItem with subtitle programmatically

I need to have a DrawerMenu with programmatically generated items, I can add the menuItems but only with a title and an icon, I want them to have a subtitle also (Like in the picture)

enter image description here

I get the Drawer by its ID, then its menu and then I add MenuItems like this (Code snippet from my MainActivity):

int id =0;
String MenuTitle = "Title of the item in menu";
NavigationView mDrawerList = (NavigationView)findViewByID(R.id.nav_view);
Menu menu = mDrawerList.getMenu();
MenuItem menuItem;
menuItem = menu.add (Menu.NONE, id, Menu.NONE, title);
menuItem.setIcon(R.drawable.ic_action_home);
menuItem.setCheckable(true);
like image 478
Enrique Alcazar Avatar asked Feb 23 '16 12:02

Enrique Alcazar


1 Answers

Currently NavigationView doesn't allow to add subTitle to it's menu.

But if you want to achieve this I would recommend you take the ListView Nested inside the NavigationView. So that you can customize your ListView cell accrding to your need.

<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/nav_header" />

        <ListView
            android:id="@+id/lst_menu_items"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</android.support.design.widget.NavigationView>

Note: Don't forget to remove app:menu from NavigationView if you are using ListView and Menu file both at the same time. it will overlap your ListView on the menu items.

like image 70
Moinkhan Avatar answered Oct 02 '22 20:10

Moinkhan