【问题标题】:How can I use FragmentManager to display Fragment A, B, C,... in a FrameLayout?如何使用 FragmentManager 在 FrameLayout 中显示 Fragment A、B、C、...?
【发布时间】:2011-12-09 02:37:07
【问题描述】:

亲爱的 StackOverflow 人,

我的 Android 应用程序目前有一个大问题。

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

我的应用程序现在在手机和平​​板电脑上的外观非常酷。

我的问题:

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

所以,这是片段 A 的屏幕截图。

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

<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 是硬编码的。

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

非常感谢您的帮助。

【问题讨论】:

    标签: android layout replace fragment


    【解决方案1】:

    使用 FragmentTransaction 替换片段。

    您可以通过编程方式替换片段。

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

    添加到后台堆栈是可选的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多