问题
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?
回答1:
You can access Activity from Fragment through interface:
- Create and interface say
LoginSuccessListener
- Implements this in your
Activity
- Inside fragment receive this listener inside
onAttach
- Use it as you needed to update
Navigation Menu
来源:https://stackoverflow.com/questions/58473262/navigation-components-switch-menu-of-navigation-drawer-for-logged-in-users