隐藏导航抽屉菜单项 - Android

Posted

技术标签:

【中文标题】隐藏导航抽屉菜单项 - Android【英文标题】:Hide a Navigation Drawer Menu Item - Android 【发布时间】:2015-11-04 11:01:12 【问题描述】:

我有一个导航抽屉。调用事件时,我想为用户隐藏我的导航菜单项之一。我该怎么做?

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

我想在索引 2 处隐藏我的抽屉式导航菜单项。该怎么做?

更新 我的导航抽屉中有 5 个菜单项,我想在调用某个事件时隐藏其中一个。

【问题讨论】:

你的意思是删除DrawerLayout列表视图中的第二项? 不,只是隐藏它。因为我想稍后再显示它 【参考方案1】:
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);
   

【讨论】:

代码有效。但是如何让它“消失”而不是“不可见” @Kakumanusivakrishna:看看 Desmond Yao 的回答。它实际上是从列表中删除它而不是让它“消失”。但这是唯一的途径 @Kakumanusivakrishna .setVisible(false) 将仅保留项目【参考方案2】:

这将作为 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);

【讨论】:

能否请您添加有关这段代码如何提供帮助的更多信息。 当您需要在运行时隐藏特定的导航菜单项时,此代码可为您提供帮助。示例: 当用户登录时。它在导航抽屉中显示配置文件菜单,否则不会。使用此代码,您可以在导航抽屉中隐藏和显示菜单项。【参考方案3】:

Kotlin 版本

 val navigationView: NavigationView = findViewById(R.id.nav_view) as NavigationView
 val nav_Menu: Menu = navigationView.getMenu()
 nav_Menu.findItem(R.id.nav_stock).setVisible(false)

【讨论】:

【参考方案4】:

您可以通过以下代码删除listview的第二项:

navDrawerItems.remove(2);
((BaseAdapter)adapter).notifyDataSetChanged();

【讨论】:

这是第三项【参考方案5】:
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);

【讨论】:

【参考方案6】:

隐藏/显示导航项

在您的 NavDrawerListAdapter 中进行如下更改,

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;
    

在activity中调用这个方法如下,

adapter.hideView(2);
//adapter.showView(2);

【讨论】:

【参考方案7】:
    //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;

【讨论】:

【参考方案8】:

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

    

【讨论】:

以上是关于隐藏导航抽屉菜单项 - Android的主要内容,如果未能解决你的问题,请参考以下文章

Android以编程方式更改导航抽屉菜单项文本

Android - 导航抽屉 - 与动态菜单项重叠的片段

Android中的导航抽屉菜单项标题颜色

Android:导航抽屉子菜单:如何折叠导航项

更改导航抽屉中菜单项的文本颜色

java 隐藏抽屉菜单项