Fragments overlapping each other

android, android-actionbar, android-fragments, fragment

Solution

You can manage your fragments by searching them by tag. When adding fragment to backstack add TAG name

transaction.addToBackStack("myCustomFragmentTag");

If you want to destroy Fragment anywhere in application :

Fragment previousInstance = getFragmentManager().findFragmentByTag("myCustomFragmentTag");
                if (previousInstance != null)
                    transaction.remove(previousInstance);

You can try override some behavior so this line of code 'll destroy initialized last Fragment

getFragmentManager().popBackStack(); 

Problem

I have an action bar with 3 tabs, each tab opens a fragment. The third tab, "Catalog", has a list: When I click on an item it opens another fragment, which is not part of the action bar: ``` public void onClick(View v) { switch (v.getId()) { case R.id.category1: Fragment cosmeticsFragment = new ActivityCosmetics(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(android.R.id.content, cosmeticsFragment); transaction.addToBackStack(null); transaction.setTransition(1); transaction.commit(); break; ... ``` This is what it looks like after that: From this point, if I go to other tab and then return to the Catalog tab, I see the 2 previous fragments overlapping each other: How do I prevent it from happening?

Original source

Related problems