Search code examples
androidnavigation-drawerandroid-architecture-navigationandroid-navigationview

Hiding Drawer item Using Android Navigation Component


I am using navigation component along with navigation drawer. If a user login with FirebaseAuth in my LoginFragment I want to hide login/signup menu from navigation drawer. Can anyone tell me how could I do that?

Navigation Drawer


Solution

  • If a user login with FirebaseAuth in my LoginFragment I want to hide login/signup menu from navigation drawer

    You can get the menu from the NavigationView attached to the navigation drawer and use removeItem(id) to remove a particular item:

    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); 
    }
    

    UPDATE

    navigation drawer is in my MainActivity

    To access activity from the fragment use requireActivity() or getActivity() like:

    ((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