Dynamic Menus in NavigationView

You can add menus dynamically by following steps :

Step1. Obtain menu object from Navigation View NavigationView.getMenu()

Step2. Add any item to the menu using Menu.add()


We can dynamically add/remove menu items. Suppose we have this menu items `

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_home"
        android:icon="@mipmap/home_icon_x48"
        android:title="Home" />
    <item
        android:id="@+id/nav_part_catalouge"
        android:icon="@mipmap/catalogue_icon_x48"
        android:title="Parts Catalogue" />
    <item
        android:id="@+id/nav_favourite"
        android:icon="@mipmap/my_favourate_x48"
        android:title="My-Favourite" />\
    <item
        android:id="@+id/nav_opencarrequest"
        android:icon="@mipmap/cart_request"
        android:title="Cart-Request" />

    <item
        android:id="@+id/nav_setting"
        android:icon="@mipmap/settings_x48"
        android:title="Settings" />
</group>


<item android:title="">
    <menu>
        <item
            android:id="@+id/nav_logout"
            android:icon="@mipmap/logout_icon_x48"
            android:title="Logout" />
    </menu>
</item>

`

In Activity we can add or remove menuitems based on our condition

protected void onCreate(Bundle savedInstanceState){
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);// your activity layout here
   NavigationView navigationView= (NavigationView) findViewById(R.id.nav_view); // navigation view which holds menu items
   navigationView.setNavigationItemSelectedListener(this);
   if(yourCondition){
          navigationView.getMenu().getItem(0).setVisible(false); //if you want to hide first item
          navigationView.getMenu().getItem(1).setVisible(true); // if you want to show second menu item should be visible
  }


}

Hope it will help.


You can re-inflate NavigationViewat runtime with 2 lines of code using public method inflateMenu. In this example i re-inflate with new_navigation_drawer_items.xml

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.new_navigation_drawer_items); //inflate new items.