4

I have some fragments which will be replaced by following method. I think there's something wrong with my code because I want to prevent from adding multiple times a fragment into the back stack. If I click on fragment B twice, all instances will be added to the back stack and pressing back button will be passed through the two created instances.

public void replaceFragment(Fragment fragment, boolean addToBackStack, boolean customAnimation) { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); String tag = fragment.getClass().getSimpleName(); if (customAnimation) { transaction.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_bottom, R.anim.slide_in_bottom, R.anim.slide_out_bottom); } transaction.replace(R.id.fragment_container, fragment, tag); // remove from back stack if exists // always return false! boolean f = manager.popBackStackImmediate(tag, 0); if (addToBackStack) { transaction.addToBackStack(tag); } transaction.commit(); } 

2 Answers 2

6

Keep it simple and just add to the back stack if needed. If the Fragment being added is the same class as the current Fragment, don't add to the back stack:

public void replaceFragment(Fragment frag) { FragmentManager manager = getSupportFragmentManager(); if (manager != null){ FragmentTransaction t = manager.beginTransaction(); Fragment currentFrag = manager.findFragmentById(R.id.content_frame); //Check if the new Fragment is the same //If it is, don't add to the back stack if (currentFrag != null && currentFrag.getClass().equals(frag.getClass())) { t.replace(R.id.content_frame, frag).commit(); } else { t.replace(R.id.content_frame, frag).addToBackStack(null).commit(); } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I really need. Thanks Daniel. I have a question. Why you passed null as back stack name? If I pass the fragment tag what would happen?
0

try this on your activity onBackPressed method :

 @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); if (fm.getBackStackEntryCount() > 0) { if (fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("your fragment tag")) { fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.