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?
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 once had this problem and found out that it was because I had accidentally deleted the
android:background
attribute that is missing on your xml code. I believe it works like when you're painting a wall,android:background
is the color that the wall will be and the other views are placed on top of that base color. When you don't paint the wall prior to positioning your views they will be on top of what was already in that wall, in your case, your other fragment. Don't know if that will help you though, good luck.I agree with Sapan Diwakar's answer. But I have found a workaround on how to do this.
First, in your activity(e.g.
activity_main
), where you have all the layouts, Add aFrameLayout
. It's height and width should bematch parent
. Also, give it anid
.Now, in your fragment which is going to replace the current layout, call
onPause()
andonResume()
. Initialise all the all the inner containers inView
. And set theirvisibility
toGONE
inonResume()
andVISIBLE
inonPause()
.NOTE: Not the
FrameLayout
which you are replacing with this fragment.Suppose you have
ViewPager
,TabLayout
,ImageView
and a custom<fragment>
inactivity_main.xml
. Add, aFrameLayout
as mentioned above.In
abcFragment.java
, inonClick()
function, addaddToBackstack(null)
intransaction
.Example code:
in xyzFragment, which is going to replace abcFragment(and everything shown in activity_main.xml), do this
Happy coding!