简体   繁体   中英

How to remove item from menu programmatically?

I've created bottom bar navigation with menu. I want to remove menu items by checking some conditions, so i want it remove using java code. I have tried it using onCreateOptionsMenu() , but somehow it did not work. I don't know what am i doing wrong, a little help would be appreciated.

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.member_activities);        
            BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomViewBar);
            BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
            menu = bottomNavigationView.getMenu();
            MenuItem menuItem = menu.getItem(0);
            menuItem.setChecked(true);
}
  @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            this.menu = menu;
            menu.removeItem(R.id.district_tab);
            return true;
        }

bottom_navigation_menu.xml:

<item
    android:id="@+id/member_tab"
    android:icon="@drawable/ic_person_outline"
    android:title="Member"/>
<item
    android:id="@+id/club_tab"
    android:icon="@drawable/ic_person_outline"
    android:title="Club"/>

<item
    android:id="@+id/district_tab"
    android:icon="@drawable/ic_person_outline"
    android:title="District"/>

<item
    android:id="@+id/ag_tab"
    android:icon="@drawable/ic_person_outline"
    android:title="AG"/>

<item
    android:id="@+id/dg_tab"
    android:icon="@drawable/ic_person_outline"
    android:title="DG"/>

onCreateOptionsMenu its for the menu in the toolbar.

For the menu in your BottomNavigationView you need to use bottomNavigationView.getMenu().removeItem(R.id.district_tab); in onCreate method.

试试这个请:

bottomNavigationView.getMenu().removeItem(R.id.district_tab);

您必须使用底部导航视图的引用来删除项目:

bottomNavigationView.getMenu().removeItem(R.id.district_tab);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM