Reputation: 340
This is my main XML
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_place" android:layout_width="wrap_content" android:layout_height="fill_parent"/>
This is my Main Activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.fragment_place, new ThirdClass());
fragmentTransaction.commit();
}
This is ThirdClass
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.test_fragment1, container, false);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.fragment_place, new FourthClass());
fragmentTransaction.commit();
return v;
}
This is the layout of ThirdClass
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Second Fragment"/></LinearLayout>
This is the FourthClass
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.test_frag, container, false);
return v;
}
And the layout
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><TextView android:layout_width=" android:layout_height=" android:text="Third Fragment"/></LinearLayout>
My question is that those fragments are being saved not replacing each other and it shows me this.
Upvotes: 0
Views: 6465
Reputation: 542
Use fragmentTransaction.replace()
instead of fragmentTransaction.add()
From the documentation:
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
Upvotes: 4