In my app I have a navigation drawer with several fragments. One of the menu from navigation drawer is for closing current visible fragment and go to previous one. To achieve above behavior I added fragment to backstack.
This is how my fragment transaction looks like
if (fragment != null) {
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment, "name");
fragmentTransaction.addToBackStack(fragment.getClass().getSimpleName());
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
I have added onBackPress()
method to handle backstack transactions. Here is the code for backpress method.
@Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() > 0) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("name");
fragmentManager.popBackStack();
if (fragment instanceof Articulos) {
mToolbar.setTitle("Articulos");
// add your code to change title of toolbar
} else if (fragment instanceof Clientes) {
mToolbar.setTitle("Clientes");
} else if (fragment instanceof Pedidos) {
mToolbar.setTitle("Pedidos");
} else if (fragment instanceof Herramientas) {
mToolbar.setTitle("Herramientas");
} else if (fragment instanceof Visor) {
mToolbar.setTitle("Visor");
}
} else {
super.onBackPressed();
}
}
onBackPressed()
method works properly as required when called on press of device back button . From navigation drawer menu for removing fragment from backstack, I have called this same method there also like this.
case 5:
title = "Cerrar";
onBackPressed();
break;
PROBLEM:
My problem is that when I call onBackPressed()
from navigation drawer, it only pop first fragment from the backstack and not the remaining ones. I debugged this method and it is getting called properly but fragments are not changing after first time.
I tried with popBackStackImmediate
too but problem still remains.
What can be the problem here?
Aucun commentaire:
Enregistrer un commentaire