I used BottomNavigationView to switch fragments. How to get currently selected menu item, to prevent reopening fragment ?
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_1:
// open fragment 1
break;
case R.id.action_2:
// open fragment 2
break;
case R.id.action_3:
// open fragment 3
break;
}
return false;
}
});
}
Get selected item at first and then
getMenu().findItem(int itemId)
I think the simplest solution for checking if the previous item is the next item is this:
Note that there is no need for iterating, and that
onNavigationItemSelected
returnstrue
, because the function consumes the event.I hope it helps someone.
Get the currently selected menu item ID using
getSelectedItemId
:This method started being available from Android Support Library 25.3.0.
Solution: