Replace a fragment programmatically

2020-06-30 09:12发布

问题:

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.

回答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();   
}


回答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.