There is a left drawer and a fragment that changes when an item in the navigation drawer is selected. The problem is that, if the "Item A" is already selected, and the user select it again, the fragment is changed for the same fragment.
To prevent this behavior, I need to know which item is already selected. I was using a attribute mLastSelectedItemPosition, but i don't think this is a good solution. Is there any way to get the current checked item from the navigation drawer?
class OnNavigationItemSelectedListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (mLastSelectedItemPosition != menuItem.getOrder()) {
// Is not the same item, so I can change the fragment.
mLastSelectedItemPosition = menuItem.getOrder();
}
mDrawerLayout.closeDrawers();
return true;
}
}
}
I do the exact same thing, have a int variable holding the selected position.
One thing to keep in mind is to save this variable onInstaceChange, because if you don`t you might be out-of-date with your drawer.
So, with that said, some code:
private static final String MENU_ITEM = "menu_item";
private int menuItemId;
...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
if (menuItemId == item.getItemId()) {
drawerLayout.closeDrawer(navigationView);
return false;
switch (item.getItemId()) {
....
}
...
drawerLayout.closeDrawer(navigationView);
item.setChecked(true);
menuItemId = item.getItemId();
return true;
}
});
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(MENU_ITEM, menuItemId);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
this.menuItemId = savedInstanceState.getInt(MENU_ITEM);
}
Something like that !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With