Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use FragmentManager to display Fragment A, B, C,... in a FrameLayout?

Dear StackOverflow people,

I have currently one big issue in my Android application.

I am using Fragments for all my activities and I read all the doc here: http://developer.android.com/guide/topics/fundamentals/fragments.html

My application has now a very cool look on phones and tablets.

My question:

I have a layout displaying a Fragments that is included in a FrameLayout (see screenshot at the bottom)

So, this is a screenshot with Fragment A.

Now, I would like when clicking on a left button, to replace the 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 hardcoded.

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

Thank a lot for your help.

enter image description here

like image 314
Waza_Be Avatar asked Oct 17 '11 08:10

Waza_Be


1 Answers

use FragmentTransaction to replace fragments.

you can do the replace of fragments programatically.

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

add to back stack is optional.

like image 149
Yashwanth Kumar Avatar answered Sep 27 '22 20:09

Yashwanth Kumar