can’t replace fragment within fragment Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of can’t replace fragment within fragment without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’ve got a ListFragment with this:

    public void fragmentSelection(Integer count) {
      Fragment fr;
      if (count == 0) {
        fr = new Fragment1();
      } else {
        fr = new Fragment2();
      }
      FragmentManager fm = getFragmentManager();
      FragmentTransaction fragmentTransaction = fm.beginTransaction();
      fragmentTransaction.replace(R.id.content, fr, fr.getClass().getName());
      fragmentTransaction.commit();
    }

here I am trying to replace the fragment content with fr (depends on count value)..

the part from XML looks like this

<fragment 
  android:id="@+id/content" 
  android:name="com.test.app.DefaultContent" 
  android:layout_width="match_parent"
  android:layout_height="match_parent">
</fragment>

Now when I want to replace fragment “content” with “fr” it do not replace it 1:1 – it adds fr down to the already current fragment (here DefaultContent) – so – why it does not replace it? What I have to do, that it replaces it and not puts the fr in addition below the current fragment

Answer

The View ID you pass to replace(), in your case R.id.content, has to be the ID of the Fragment’s parent View, not the original Fragment itself.

That means you have to set android:id="@+id/content" to the Fragment’s parent, like this:

<FragmentLayout
    android:id="@+id/content" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment 
        android:name="com.test.app.DefaultContent" 
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FragmentLayout>

Or, if that does not work for you, set a new ID to the parent and use it for replace().

We are here to answer your question about can’t replace fragment within fragment - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji