Re-selecting the correct NavigationView menu item after pressing the back button

I have an Android app that has a NavigationView with 4 fragments. I can move between fragments through the navigation menu, and when I select another fragment, I added the previous fragment to the back stack to provide the functionality of the back button.

My problem is that when I click the back button to go to the previous fragment, the NavigationView still shows the old fragment as the selected fragment. If possible, I want to update the selected option as a fragment on the screen.

Example:
I start with A and select B from the NavigationView. The current screen is B, and the NavigationView displays the selected item as B. If I press the back button, my current screen will again become A, but the NavigationView displays B as the selected item.

Here is my onNavigationItemSelected method:

public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); HomeFragment fragment = null; Class type = null; switch (id) { case R.id.nav_home: type = HomeNavigationFragment.class; break; case R.id.nav_groups: type = GroupsNavigationFragment.class; break; case R.id.nav_profile: type = ProfileNavigationFragment.class; break; case R.id.nav_messages: type = MessageNavigationFragment.class; break; } fragment = HomeFragment.newInstance(mUser, type); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.fragment_container, fragment).addToBackStack("fragment" + code++).commit(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } 

Thanks.

+6
source share
1 answer

I fixed my onBackPressed override problem as follows:

 @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { FragmentManager manager = getSupportFragmentManager(); if(manager.getBackStackEntryCount() > 0) { super.onBackPressed(); HomeFragment currentFragment = (HomeFragment) manager.findFragmentById(R.id.fragment_container); if(currentFragment instanceof HomeNavigationFragment){ mNavigationView.getMenu().getItem(0).setChecked(true); } else if(currentFragment instanceof GroupsNavigationFragment){ mNavigationView.getMenu().getItem(2).setChecked(true); } else if(currentFragment instanceof ProfileNavigationFragment){ mNavigationView.getMenu().getItem(1).setChecked(true); } else if(currentFragment instanceof MessageNavigationFragment){ mNavigationView.getMenu().getItem(3).setChecked(true); } } } } 
+9
source

All Articles