Android - Add bottom navigation view dynamically

2019-07-31 02:02发布

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?

3条回答
神经病院院长
2楼-- · 2019-07-31 02:43

try to do this

bottomNavigationView = new BottomNavigationView(ActivityName.this);

or

bottomNavigationView = new BottomNavigationView(getApplicationContext());
查看更多
家丑人穷心不美
3楼-- · 2019-07-31 02:47

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~

查看更多
Explosion°爆炸
4楼-- · 2019-07-31 02:52

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

查看更多
登录 后发表回答