How can I use the FragmentManager to display fragments A, B, C, ... in FrameLayout?

Dear StackOverflow People,

I currently have one big problem in an Android app.

I use snippets for all my activities, and I read the entire document here: http://developer.android.com/guide/topics/fundamentals/fragments.html

My application now scans phones and tablets very cool.

My question is:

I have a layout showing fragments that are included in FrameLayout (see screenshot below)

So this is a screenshot with fragment A.

Now, I would like by clicking on the left button to replace fragment A with fragment B, or C, or ...

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.stackoverflow.question.FRAGMENT_A" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> </FrameLayout> 

As you can see in my xml, FRAGMENT_A is hard-coded.

Imagine that I want to switch between 6 different fragments, what am I doing? Put all my 6 snippets in XML or is there a way to replace FRAGMENT_A programmatically with FRAGMENT_B, C, D, E, etc.

Many thanks for your help.

enter image description here

+8
android replace layout fragment
source share
1 answer

use FragmentTransaction to replace fragments.

You can replace fragments programmatically.

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); FragmentB fb = new FragmentB(); ft.replace(R.id.list, fb); ft.addToBackStack("replacingFragmentA"); ft.commit(); 

add to the back stack is optional.

+14
source share

All Articles