导航组件:导航抽屉的切换菜单(适用于已登录的用户) [英] Navigation Components: Switch Menu of Navigation Drawer (for logged in users)
问题描述
我正在使用新的Navigation Components库.我有一个可以正常工作的导航抽屉.
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);
但是,在我看来,这似乎不起作用(我无法从片段中获取navigationView).导航组件如何实现这一目标?
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?
推荐答案
您可以通过界面从 Fragment 访问活动:
You can access Activity from Fragment through interface:
- 创建并说出
LoginSuccessListener
- 在您的
Activity
中实现
- 内部片段在
onAttach
中接收此侦听器
- 根据需要使用它来更新
Navigation Menu
- 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
这篇关于导航组件:导航抽屉的切换菜单(适用于已登录的用户)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!