Search code examples
javaandroidnavigationandroid-architecture-navigation

Navigation Components: Switch Menu of Navigation Drawer (for logged in users)


I am using the new Navigation Components library. I have a Navigation Drawer in place that works perfectly fine.

If my user logs in I want to change the menu of the Navigation Drawer. Specifically, I want to change the "Login" item to "Logout" from within a fragment.

All the solutions I found online didn't use Navigation Components. So therefore, they recommended something like this:

// Get the navigationView and swap the menu
NavigationView navigationView = view.findViewById(R.id.nav_view);
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.activity_main_drawer_logged_in);

However, this doesn't seem to work in my case (I cannot get the navigationView from within a fragment). How does one achieve this with Navigation Components?


Solution

  • You can access Activity from Fragment through interface:

    1. Create and interface say LoginSuccessListener
    2. Implements this in your Activity
    3. Inside fragment receive this listener inside onAttach
    4. Use it as you needed to update Navigation Menu