0

First of all, I want to explain what "programmatically" means, in my case, it means "No XML at all".

My goal is rather simple, but I'm struggling with doing everything programmatically:

  1. Put a BottomNavigationView at the bottom of the screen

  2. Inflate BottomNavigationView with 4 buttons, each has an icon but no title

  3. Set on select listener and when selected, find out which item is selected

Here's the code I have for 1 and 2, but not 3:

public class BottomBarLayout extends RelativeLayout {
    BottomNavigationView bottomBar;

    public BottomBarLayout(Context context) {
        super(context);

        configureBottomBar();
    }

    private void configureBottomBar() {
        bottomBar = new BottomNavigationView(this.getContext());

        // Inflate bottom bar with 4 items without titles but with icons
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.getMenu().add(null).setIcon(R.drawable.ic_...);
        bottomBar.setOnNavigationItemSelectedListener(menuItem -> onSelectNavigationItem(menuItem));

        // Add layout rules to stick bottomBar to bottom of screen
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        addView(bottomBar, params);
    }
}

private boolean onSelectNavigationItem(MenuItem item) {
    // -------------------->Question here<------------------------
    return true;
}

My question is, in onSelectNavigationItem listener, how do I know which item is selected? I didn't assign an id to any of the 4 items. If I could assign ids, how? If not, how do I know which item is selected? Thank you.

K.Wu
  • 3,553
  • 6
  • 31
  • 55
  • 1
    Use one of the `Menu#add()` methods that takes an item ID; e.g., [`add(int, int, int, CharSequence)`](https://developer.android.com/reference/android/view/Menu.html#add(int,%20int,%20int,%20java.lang.CharSequence)). – Mike M. Jan 28 '19 at 19:29
  • 1
    @MikeM. Thanks, it solves my problem. – K.Wu Jan 28 '19 at 19:50

0 Answers0