Shared “checkable” behavior across all groups in NavigationView

I’m not sure why Google not only did not provide a straightforward API to customize such basic property, but also chose to set the default behavior to be rather undesirable in most cases.

I’ve asked a question on Stack Overflow and on the next day I provided a quick solution. Here’s the snippet:

Step 1: Remove

android:checkableBehavior="single"

from all groups.

Step 2: Add

android:checkable="true"

to all items in all groups.

Step 3: Add the following logic to your OnNavigationItemSelectedListener:

mNavigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    if (mPreviousMenuItem != null) {
                        mPreviousMenuItem.setChecked(false);
                    }
                    mPreviousMenuItem = menuItem;
                    //...
                    changeCurrentFragment(...);
                    return true;
                }
            });

Leave a Reply

Your email address will not be published. Required fields are marked *