2011-10-17 54 views
8

尊敬的StackOverflow人,如何使用FragmentManager在FrameLayout中显示片段A,B,C ...?

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

我使用的片段对我的所有活动,我在这里阅读所有的文档:http://developer.android.com/guide/topics/fundamentals/fragments.html

我的应用程序现在已经在手机和平​​板电脑一个非常酷的样子。

我的问题:

我有一个布局显示包含在一个FrameLayout里(见下方截图)

所以,这是与片段A.一个截图片段

现在,我想单击左侧按钮时,用碎片B或C替换碎片A,或者...

<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_B,C,D,E等编程替换FRAGMENT_A。

非常感谢您的帮助。

enter image description here

回答

14

使用FragmentTransaction更换片段。

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

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

加回栈是可选的。

相关问题