首页 > 解决方案 > 使用 Android 导航组件隐藏抽屉项目

问题描述

我正在使用导航组件和导航抽屉。如果用户使用 FirebaseAuth 登录,LoginFragment我想从导航抽屉中隐藏登录/注册菜单。谁能告诉我我该怎么做?

导航抽屉

标签: androidnavigation-drawerandroid-architecture-navigationandroid-navigationview

解决方案


如果用户在我的 LoginFragment 中使用 FirebaseAuth 登录,我想从导航抽屉中隐藏登录/注册菜单

您可以从NavigationView附加到导航抽屉的菜单中获取菜单并用于removeItem(id)删除特定项目:

if (userLoggedIn) { // Set that to your logic when the user logged in.
    removeItem(R.id.singup); // adjust that to the id you set to sign up
    removeItem(R.id.login); // adjust that to the id you set to login 
}

public removeItem(int id) {
    NavigationView navView = findViewById(R.id.foo); // Add your NavigationView id
    Menu menu = navView.getMenu();
    if (menu.findItem(id) != null) // Make sure that the item exists in the menu
        menu.removeItem(id); 
}

更新

导航抽屉在我的 MainActivity

要从片段中访问活动,请使用requireActivity()getActivity()类似:

((MainActivity) requireActivity()).removeItem(R.id.login); // adjust that to the id you set to sign up
((MainActivity) requireActivity()).removeItem(R.id.signup); // adjust that to the id you set to login 

推荐阅读