Creating Dynamic Navigation Drawer Menu in Android

compodoc

Many times We learn new things where we are trying to meet the app design requirement. I also come across a situation when I have to show dynamic menu items from server in android conventional navigation drawer.

One option for me to was just use Recyclerview with header footer to fulfill the requirement. But that day I was having enough time to experiment and tried to explore more about navigation view api in android.

So my code here is

A view which contain drawer and navigation menu.

public void getCategories() {

        ApiInterface apiService =
                ApiClient.getClient(this).create(ApiInterface.class);
        Call call = apiService.getAllCategories();

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                AllCategories feed = response.body();
                // CommonUtils.hideCustomProgress(loaderlayout);
                if (feed != null) {
                    if (feed.status.equalsIgnoreCase("OK")) {

                        try {

                            NavigationView navView = (NavigationView) findViewById(R.id.nav_view);

                            Menu menu = navView.getMenu();
                            Menu submenu = menu.addSubMenu(R.id.groupcategory,Menu.NONE,2,"Categories");
                            map.clear();
                            submenu.clear();
                            navView.invalidate();

                            for (AllCategories.GetData data:
                            feed.GetData) {

                                map.put(data.cat_ID,data.slug);
                                MenuItem item=submenu.add(R.id.groupcategory,data.cat_ID,data.cat_ID,data.cat_name);
                                item.setIcon(R.mipmap.ic_launcher);
                                item.setCheckable(true);
                            }
                            navView.invalidate();


                        }catch (Exception e){

                        }


                    } else {

                    }
                }else {


                }


            }

            @Override
            public void onFailure(Call call, Throwable t) {
                // CommonUtils.hideProgress(getActivity());
                //onLoginFailed();
                t.printStackTrace();
            }
        });


    }

https://gist.github.com/CodeNextGen/b6f4133bc6591ed206947bee5e0c9fd1

What we are doing here is just adding a submenu named 'categories'

 NavigationView navView = (NavigationView) findViewById(R.id.nav_view);

 Menu menu = navView.getMenu();

 Menu submenu = menu.addSubMenu(R.id.groupcategory,Menu.NONE,2,"Categories");

After that from web service response sub categories are added under 'Categories' Menu.

                            map.clear();
                            submenu.clear();
                            navView.invalidate();

                            for (AllCategories.GetData data:
                            feed.GetData) {

                                map.put(data.cat_ID,data.slug);
                                MenuItem item=submenu.add(R.id.groupcategory,data.cat_ID,data.cat_ID,data.cat_name);
                                item.setIcon(R.mipmap.ic_launcher);
                                item.setCheckable(true);
                            }
                            navView.invalidate();

We are storing category data in hash map to use it in future when subcategories item is clicked.you can find this in

 map.put(data.cat_ID,data.slug);

Now you have rendered categories in navigation drawer now you can fetch post related to particular sub category when it is clicked . Check code snippets

 @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int group_id=item.getGroupId();
        int id = item.getItemId();
       // Toast.makeText(getApplicationContext(),group_id+" "+id,Toast.LENGTH_LONG).show();
        if(group_id==R.id.groupcategory){

                    if(map.size()>0){

                String slug=map.get(id);
               // Toast.makeText(getApplicationContext(),title,Toast.LENGTH_LONG).show();
                Bundle bundle = new Bundle();
                bundle.putString("slug",slug);
                currentFragment(106,bundle);
            }

        }else {
            // Handle navigation view item clicks here.


            if (id == R.id.nav_home) {

                currentFragment(105, null);

            }

//            if (id == R.id.nav_nearby) {
//
//                startActivity(new Intent(this, VideoListDemoActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
//                return true;
//
//            }
//
//            if (id == R.id.nav_my_jyot) {
//
//                startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
//                return true;
//
//            }


            if(id == R.id.nav_rating){

                new EasyRatingDialog(this).rateNow();


            }

            if(id == R.id.nav_spread_love){

                CommonUtils.ShareApp(this);

            }

            if(id == R.id.nav_contactus){

                String mailto = "mailto:";

                Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                emailIntent.setData(Uri.parse(mailto));

                try {
                    startActivity(emailIntent);
                } catch (ActivityNotFoundException e) {
                    //TODO: Handle case where no email app is available
                }

            }

        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

Check Group ID plays a very important role when deciding about click inside drawer item.

You may find full code snipped where I have used it in my project.

https://gist.github.com/CodeNextGen/5996e8bd99c7f4e451d91a5ba5117452

Output

{.alignnone .size-medium .wp-image-2135 width="150" height="300"}

Hope this post will be helpful it you don't need too much customization, If you need too much customization then I would recommend you to go with Recycler View inside Drawer.

Thanks for reading,Stay tuned for more.


Tagged with:
CodeNextGen
Written by Sanjeev Kumar

Get notifications about new posts on Twitter, RSS or Email.