如何使用 FragmentManager 在 FrameLayout 中显示 Fragment A、B、C、...? [英] How can I use FragmentManager to display Fragment A, B, C,... in a FrameLayout?

查看:17
本文介绍了如何使用 FragmentManager 在 FrameLayout 中显示 Fragment A、B、C、...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的 StackOverflow 用户:

Dear StackOverflow people,

我的 Android 应用程序目前存在一个大问题.

I have currently one big issue in my Android application.

我在所有活动中都使用 Fragments,我在这里阅读了所有文档:http://developer.android.com/guide/topics/fundamentals/fragments.html

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.

我的问题:

我有一个显示包含在 FrameLayout 中的 Fragments 的布局(请参阅底部的屏幕截图)

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

所以,这是片段 A 的截图.

So, this is a screenshot with Fragment A.

现在,我想在单击左键时将片段 A 替换为片段 B、C 或...

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>

正如您在我的 xml 中看到的,FRAGMENT_A 是硬编码的.

As you can see in my xml, FRAGMENT_A is hardcoded.

假设我想在 6 个不同的片段之间切换,我应该怎么做?将我所有的 6 个 Fragment 都放在 XML 中,或者有没有办法以编程方式将 FRAGMENT_A 替换为 FRAGMENT_B、C、D、E 等

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.

非常感谢您的帮助.

推荐答案

使用 FragmentTransaction 替换片段.

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.

这篇关于如何使用 FragmentManager 在 FrameLayout 中显示 Fragment A、B、C、...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆