Hide a Navigation Drawer Menu Item - Android
Asked Answered
P

10

84

I have a navigation drawer. When an event is called, I want to hide one of my navigation menu item for user. How can I do that?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sliding_menu);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout1);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu1);

    navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Profil
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    // Prospek
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    // Announcement
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true,
            cariTotal("http://192.168.0.23/api/android/announcement/").toString()));
    // Logout
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));

    // Recycle the typed array
    navMenuIcons.recycle();
    //set event
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mDrawerList.setAdapter(adapter);
    // enabling action bar app icon and behaving it as toggle button
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.string.app_name,
            R.string.app_name
    ){
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            //mDrawerList.bringToFront();
            //mDrawerLayout.requestLayout();
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        // on first time display view for first nav item
        displayView(0);
    }
}
private void displayView(int position) {
    // update the main content by replacing fragments
    android.app.Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new ProfilFragment();
            break;
        case 2:
            fragment = new ProspekFragment();
            break;
        case 3:
            fragment = new AnnouncementFragment();
            break;
        case 4:
            Logout();
            break;
        default:
            break;
    }

    if (fragment != null) {
        android.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("SlidingMenu", "Error in creating fragment");
    }
}

I want to hide my navigation drawer menu item at index 2. How to do that?

UPDATE I have 5 menu items in my navigation drawer, I want to hide one of them when some event is called.

Pamalapamela answered 12/8, 2015 at 2:16 Comment(2)
Do you mean delete the second item in the list view of DrawerLayout?Meng
no, just hide it. because i want to show it again laterPamalapamela
C
243
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hideItem();
  }


private void hideItem()
   {
     navigationView = (NavigationView) findViewById(R.id.nav_view);
     Menu nav_Menu = navigationView.getMenu();
     nav_Menu.findItem(R.id.nav_settings).setVisible(false);
   }
Candra answered 5/3, 2016 at 18:56 Comment(3)
Code works.But how to make it "gone" instead of "invisible"Filling
@Kakumanusivakrishna : Look at Desmond Yao's answer. It's actually remove it from list instead make it "gone". But that's the only path to takeVaccinate
@Kakumanusivakrishna .setVisible(false) will keep item in gone onlyWringer
Q
27

This will work as setInvisibility(GONE):

 Menu nav_Menu = navigationView.getMenu();
 nav_Menu.findItem(R.id.nav_profile).setVisible(false);
 nav_Menu.findItem(R.id.menu_login).setVisible(true);
 nav_Menu.findItem(R.id.menu_logout).setVisible(false);
 nav_Menu.findItem(R.id.menu_regsitration).setVisible(true);
Quick answered 27/2, 2016 at 8:9 Comment(3)
Could you please add more information on how this piece of code helps.Castano
when you need to hide specific navigation menu item on runtime this code is help you. example:Quick
when user is login. its show profile menu in navigation drawer otherwise not. using this code you can hide and show menu item in navigation drawer.Quick
S
8

Kotlin version

val navigationView: NavigationView = findViewById(R.id.nav_view)
val navMenu: Menu = navigationView.menu
navMenu.findItem(R.id.nav_remove_ads).isVisible = true
Stayathome answered 28/2, 2019 at 22:50 Comment(0)
M
4

You can delete the second item of listview via following code:

navDrawerItems.remove(2);
((BaseAdapter)adapter).notifyDataSetChanged();
Meng answered 12/8, 2015 at 2:43 Comment(1)
That's the third itemSawn
P
3
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

Menu menu =navigationView.getMenu();

MenuItem target = menu.findItem(R.id.nav_target);

target.setVisible(false);
Phosphoric answered 14/9, 2018 at 12:47 Comment(0)
C
1

Hide/Show Navigation item

Make changes in your NavDrawerListAdapter as follow,

public class MyListAdapter extends BaseAdapter {

    Context context;
    ArrayList<ItemListModel> listMenuItem;
    ArrayList<ItemListModel> listMenuItem1;
    int hideViewIndex = -1;

    public MyListAdapter(Context context, ArrayList<ItemListModel> listMenuItem) {
        this.context = context;
        this.listMenuItem = listMenuItem;
        listMenuItem1=new ArrayList<ItemListModel>(listMenuItem);
    }

    @Override
    public int getCount() {
        return listMenuItem.size();
    }

    @Override
    public Object getItem(int position) {
        return listMenuItem.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder
    {
        private ImageView imgLogo;
        private TextView txtItemName;
    }

    public void hideView(int pos)
    {
        listMenuItem.remove(pos);
        notifyDataSetChanged();
    }

    public void showView(int pos)
    {
        listMenuItem.add(pos, listMenuItem1.get(pos));
        notifyDataSetChanged();
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if(convertView == null)
        {
            LayoutInflater myLayoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = myLayoutInflater.inflate(R.layout.activity_item_list, null);
            viewHolder = new ViewHolder();
            viewHolder.imgLogo = (ImageView) convertView.findViewById(R.id.imgLogo);
            viewHolder.txtItemName = (TextView) convertView.findViewById(R.id.txtItemName);
            convertView.setTag(viewHolder);
        }
        else
        {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        ItemListModel itemListModel = listMenuItem.get(position);
        viewHolder.imgLogo.setImageDrawable(itemListModel.getImageLogo());
        viewHolder.txtItemName.setText(itemListModel.getStrItemName());

        return convertView;
    }

and call this method in activity as follow,

adapter.hideView(2);
//adapter.showView(2);
Claudio answered 12/8, 2015 at 4:24 Comment(0)
B
1
    //hide logout menu item when the user is not loggrd in
    //Checking the condition whether the user is logged in or not

    if (!SharedPrefManager.getmInstance(this).isLoggedIn()){
        Menu nav_Menu = navigationView.getMenu();
    nav_Menu.findItem(R.id.nav_logout).setVisible(false);
    }


 //SharedPrefManager .java class where we define the isLoggedIn Method()

import android.content.Context;
import android.content.SharedPreferences;

import com.motortrade.motortrade.t_Model.User;

public class SharedPrefManager {

private static final String SHARED_PREF_NAME = "my_shared_pref";

private  static SharedPrefManager mInstance;
private Context mCtx;

private SharedPrefManager(Context mCtx){
    this.mCtx = mCtx;
}

public static synchronized SharedPrefManager getmInstance(Context mCtx){
    if (mInstance == null){
        mInstance = new SharedPrefManager(mCtx);
    }
    return mInstance;
}

public boolean isLoggedIn(){
    SharedPreferences preferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

   return preferences.getInt("user_id", -1) != -1;
}
Bouzoun answered 24/10, 2018 at 6:33 Comment(0)
E
1
navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.nav_profile).setVisible(false);
Evaporation answered 13/4, 2022 at 7:55 Comment(0)
D
0

NavigationView navigationView;

    mapIntentActivity = getIntent();
    navItemString = mapIntentActivity.getStringExtra("success");

    if(navItemString != null) {

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        Menu nav_Menu = navigationView.getMenu();
        nav_Menu.findItem(R.id.nav_car).setVisible(false);

    }
Dufrene answered 3/1, 2018 at 20:9 Comment(0)
O
0

If we need to hide the menu item permanently (not temporary and programmatically), we can hide it in the XML view, in the menu.xml file by adding line android:visible="false":

    <item
    android:id="@+id/action_create"
    android:title="@string/menu_action_create"
    android:visible="false" />
Overcash answered 24/9, 2022 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.