Reputation: 5016
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;
}
}
}
Upvotes: 3
Views: 3161
Reputation: 3191
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 !
Upvotes: 7
Reputation: 88
I think this will help you.
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
Toast.makeText(getApplicationContext(),"You have selected " +position,Toast.LENGTH_LONG).show();
}
}
Upvotes: 0