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?
In short when you add a fragment then it calls life cycle methods from onAttach() to onResume(). When you click back press button on an android device then fragment C, fragment B, and Fragment A go through some life cycle methods like below.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction.
A Fragment is a combination of an XML layout file and a java class much like an Activity . Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities.
You are doing two things wrong here:
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With