Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update selected state of navigation drawer after back press

Whats the proper way to handle the selected state of the navigation drawer after back press?

I have a navigation drawer with n entries (in a listview) like the SDK sample in Android Studio. When i click on the navigation drawer entries i want them to be added to the back stack, so i can move back to them.

In onNavigationDrawerItemSelected(int pos) i have

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (position == 0) {
            transaction.replace(R.id.container, new FragmentA());
        } else if (position == 1) {
            transaction.replace(R.id.container, new FragmentB());
        } else {
            transaction.replace(R.id.container, new FragmentC());
        }
        transaction.addToBackStack(null);
        transaction.commit();

When i click on the second entry in the drawer, B gets selected and replaces A. If i click the back button afterwards, Fragment A is shown again like it should, but B is still selected in the navigation drawer.

How can i get the selection status of the drawer updated after pressing back?

Somehow i need a call to mDrawerListView.setItemChecked(position, true); or NavigationDrawerFragment.selectItem(int position). But to which position? How do i remeber it?

Intercept with onBackPressed?

@Override
    public void onBackPressed() {}

But how do i know which fragment is active again? And to which position it corresponds.

Is there some easy solution i am blind to see? It seems that using back in combination with the navigation drawer and updating the selection status is a standard pattern.

like image 462
spatialist Avatar asked Jan 07 '15 17:01

spatialist


1 Answers

It's actually simple. You already have your navigation view in Drawer layout. For each item pressed, it opens the respective fragment, right? Now go the onCreateView of each fragment and do this...

NavigationView navigationView = getActivity().findViewById(R.id.navigation_view);
        navigationView.setCheckedItem(R.id.this_fragment's_item);

Also, In your Main Activity where you're handling item click, use an if statement such that

if (navigation_view.getMenu().findItem(R.id.account_nav).isChecked())   
  drawer_layout.closeDrawer(GravityCompat.START);

The above avoids creating multiple instances of a fragment on top of itself.

like image 174
Brian Gachugu Avatar answered Sep 30 '22 05:09

Brian Gachugu