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

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


I had the same problem and saw all the answers, but none of them contained my mistake! Before trying to replace the current fragment, I was showing the default fragment in the xml of the container activity like this:

<FrameLayout
    android:id="@+id/fragment_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="....ShopFragment"
        android:id="@+id/fragment"
        tools:layout="@layout/fragment_shop" />
</FrameLayout>

after that, although i was passing the FrameLayout to the fragmentTransaction.replace() but i had the exact problem. it was showing the second fragment on top of the previous one.

The problem fixed by removing the fragment from the xml and showing it programmatically in the onCreate() method of the container activity for the default preview on the start of the program like this:

    fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_frame_layout,new ShopFragment());
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

and the container activity xml:

<FrameLayout
    android:id="@+id/fragment_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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.


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.