Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...