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:
Put a BottomNavigationView at the bottom of the screen
Inflate BottomNavigationView with 4 buttons, each has an icon but no title
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.