1

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 Answers3

2

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~

Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
0

try to do this

bottomNavigationView = new BottomNavigationView(ActivityName.this);

or

bottomNavigationView = new BottomNavigationView(getApplicationContext());
  • java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library. This error is occured BottomNavigationView constructor. –  May 11 '17 at 12:46
0

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

Arnav Rao
  • 6,692
  • 2
  • 34
  • 31
  • Yes, I know. But I try to create without menu xml file. Is is possible? –  May 11 '17 at 13:07
  • I tried and could not reproduce the issue of Menu object being null. – Arnav Rao May 11 '17 at 13:35
  • My problem is not about xml file. I don't want to create a xml under res/menu. I try to create 'new BottomNavigationView()' dynamically and add to layout. –  May 11 '17 at 13:54
  • Yes, I was able to create BottomNavigationView pragmatically without any issue using latest versions. – Arnav Rao May 12 '17 at 12:42