Replace a fragment programmatically

35,139

Solution 1

You should always add, remove and replace your fragments programatically. As such I suggest you replace your F-1, F-2 and F-3 fragments with containers such as FrameLayout.

Basically instead of having a <fragment/> element as F-1 you make it a <FrameLayout/> element. Then you perform a fragment transaction in your FragmentActivity's onCreate:

Fragment1 f1 = new Fragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.f1_container, f1); // f1_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();  

Now, Suppose you have done this for F-1, F-2 and F-3. You then replace f2 with f4 by doing the same thing again in your OnClickListener:

public void onClick(View v) {
    Fragment4 f4 = new Fragment4();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.f2_container, f4); // f2_container is your FrameLayout container
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();   
}

Solution 2

Keep only FrameLayout as placeholders for the fragment in the XML. In the OnCreate load the fragments in the framelayout. OnClick of the fragment, give that particular FrameLayout's id to replace by Fragment4.

Share:
35,139
AndroidDev
Author by

AndroidDev

Updated on July 09, 2022

Comments

  • AndroidDev
    AndroidDev almost 2 years

    I have three fragments as shown in below figure. I have added all these three fragments in LinearLayout using .xml file and when my launcher activity starts I load that .xml layout using setContentView.

    I have some controls on fragment2. Clicking on any one loads the fragment4 programmatically using FragmentTransaction and commit method. This fragments is added to the screen but the problem is the prgrammatically added fragment4 take the whole screen area. What can be the problem?

    Note: On any item click at f2 I want to replace only f2 with new fragment f4. Keep in mind I have added f1, f2, f3 through xml layout file and adding new fragment f4 programmatically.

    enter image description here

  • AndroidDev
    AndroidDev about 12 years
    Do you have any reference so that I can take an example from there?
  • AndroidDev
    AndroidDev about 12 years
    Thanks. OK what I understand is Dont put fragments directly into xml layout. Put framelayouts in place of fragment elements. And while replacing f4 with f2 use frame of f2. Am I right? You can give reference site to check it out.