Fragment is not being replaced but put on top of the previous one

Activity:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

Fragment1 fragment = new Fragment1();
Fragment2 fragment2 = new Fragment2();

transaction.replace(R.id.Fragment1, fragment);
transaction.addToBackStack(null);
transaction.commit();

FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.Fragment1, fragment2);
transaction2.addToBackStack(null);
transaction2.commit();

Code in the view:

<fragment
    android:id="@+id/Fragment1"
    android:name="com.landa.fragment.Fragment1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/include1" /> 

The problem is, the content doesn't really get replaced - it gets put on top (so it overlaps).

When I click back, the first fragment gets shown properly (without the second), but initially both are visible (I want only the last one to be visible).

What am I missing here?


You are doing two things wrong here:

  1. You cannot replace a fragment that is statically placed in an xml layout file. You should create a container (e.g. a FrameLayout) in the layout and then add the fragment programatically using FragmentTransaction.

  2. FragmentTransaction.replace expects the id of the container that contains the fragment and not the id of the fragment as the first parameter. So you should pass the first argument as the id of the container that you added the first fragment to.

You can refer to this link for more details.


I had a similar problem but my issue was that I was using two different Fragment managers: One from getSupportFragmentManager() and one from getFragmentManager(). If I added one fragment with the SupportFragmentManager and then tried replacing the fragment with the FragmentManager, the fragment would just get added on top. I needed to change the code so that the same FragmentManager would be used and that took care of the issue.


The android developer site suggests the use of a FrameLayout to load fragments dynamically at run-time. You have hard-coded the fragment in your xml file. So it cannot be removed at run-time as mentioned in this link:

http://developer.android.com/training/basics/fragments/creating.html

this link shows how to add fragments through your program:

http://developer.android.com/training/basics/fragments/fragment-ui.html