Android - Add bottom navigation view dynamically

2019-07-31 02:36发布

问题:

I try to add a bottom navigation view dynamically. I know that I add a navigation view inside activity's xml file.

<android.support.design.widget.BottomNavigationView
   android:id="@+id/navigation"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_gravity="start"
   design:menu="@menu/items" />

I don't want to create a item xml file. I used below code to create navigation bar.

    bottomNavigationView = new BottomNavigationView(this);
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    bottomNavigationView.setLayoutParams(params);

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.viewLayout);
    layout.addView(bottomNavigationView);

    Menu menu = bottomNavigationView.getMenu();
    menu.add(0, i, Menu.NONE, "TEXT");

menu.add throws an error.

android.support.v7.view.menu.MenuBuilder.size()' on a null object reference

How can I add a navigation view dynamically?

回答1:

This is a bug of BottomNavigationView.

Here is the bug reference: https://issuetracker.google.com/issues/37124043

This has been fixed in support library 25.0.1. Update your support library and try again.

Hope this will help~



回答2:

try to do this

bottomNavigationView = new BottomNavigationView(ActivityName.this);

or

bottomNavigationView = new BottomNavigationView(getApplicationContext());


回答3:

You can define menu xml and inflate it calling inflateMenu method on BottomNavigationView object.

If you need to add any additional menu items, you can do by getting menu object and adding items to menu object.

Menu menu = bottomNavigationView.getMenu();