2011-10-17 56 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(); 

加回棧是可選的。

相關問題