Menardo
Menardo

Reputation: 73

Navigation drawer does not retain selected item

Having problems with retaining the selected item in the NavigationDrawer when I clicked on an item that is one a different group (special).

    ...
    <item
        android:id="@+id/item_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/drawer_notification"
        android:visible="true" />
</group>
<group android:id="@+id/special">
    <item
        android:id="@+id/item_settings"
        android:icon="@drawable/ic_settings_48dp"
        android:title="@string/drawer_settings" />
    <item
        android:id="@+id/item_feedback"
        android:icon="@drawable/ic_chat_bubble_black_24dp"
        android:title="@string/drawer_feedback" />

    <item
        android:id="@+id/item_logout"
        android:icon="@drawable/ic_arrow_back_black_24dp"
        android:title="@string/drawer_logout" />

</group>

Here's the switch case in my MainActivity:

@Override public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);

switch (menuItem.getItemId()) {
case R.id.item_notifications:
    mCurrentSelectedPosition = 6;
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.container, BaseFragment.newInstance("Notifications"))
        .commit();
    mDrawerLayout.closeDrawers();
    return true;

  case R.id.item_settings:
    mCurrentSelectedPosition = 7;
    mDrawerLayout.closeDrawers();
    Snackbar.make(findViewById(R.id.container), "Settings", Snackbar.LENGTH_SHORT).show();
    return true;

  case R.id.item_feedback:
    mCurrentSelectedPosition = 8;
    mDrawerLayout.closeDrawers();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, FeedbackFragment.getInstance())
            .commit();
    return true;

  case R.id.item_logout:
    mDrawerLayout.closeDrawers();
    session.logoutUser(MainActivity.this);
    return true;
  }
}

I don't see anything wrong with my code. It's just that when I clicked on another group in the drawer the navigationDrawer does not retain the item that I selected.

Upvotes: 1

Views: 154

Answers (1)

Harin
Harin

Reputation: 2423

You need to add this line in menu group:

android:checkableBehavior="single"

which will help you to preserve the selected state.

<group android:id="@+id/special" 
       android:checkableBehavior="single">
    <item
        android:id="@+id/item_settings"
        android:icon="@drawable/ic_settings_48dp"
        android:title="@string/drawer_settings" />
    <item
        android:id="@+id/item_feedback"
        android:icon="@drawable/ic_chat_bubble_black_24dp"
        android:title="@string/drawer_feedback" />

    <item
        android:id="@+id/item_logout"
        android:icon="@drawable/ic_arrow_back_black_24dp"
        android:title="@string/drawer_logout" />

</group>

Check this official blog post for more reference...

Hope it will help.

Upvotes: 1

Related Questions