I have an android application which has a NavigationView with 4 fragments. I can navigate between fragments via navigation menu and when I select another fragment, I added the previous fragment into back stack to provide back button functionality.
My problem is that when I press back button to go to previous fragment, the NavigationView still shows old fragment as the selected fragment. If it is possible I want to update selected option as the fragment on the screen.
Example:
I start from A, and select B from NavigationView. The current screen is B and NavigationView shows the selected item as B. If I press back button my current screen becomes A again but NavigationView shows B as 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.
I fixed my problem with overriding onBackPressed like this:
@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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With