Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a fragment programmatically

Tags:

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

like image 902
AndroidDev Avatar asked Apr 12 '12 11:04

AndroidDev


People also ask

How do I replace one fragment with another?

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.

What is FragmentContainerView?

FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout , so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.

What is FragmentManager in android?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.


1 Answers

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();    } 
like image 140
CodePrimate Avatar answered Sep 30 '22 13:09

CodePrimate