2011-10-17 6 views
8

Caro StackOverflow persone,Come posso usare FragmentManager per visualizzare Frammento A, B, C, ... in un FrameLayout?

Attualmente ho un grosso problema nella mia applicazione Android.

Sto usando frammenti di tutte le mie attività e ho letto tutto il documento qui: http://developer.android.com/guide/topics/fundamentals/fragments.html

La mia applicazione ha ora un look molto fresco su telefoni e tablet.

La mia domanda:

Ho un layout di visualizzazione di un Frammenti che è incluso in un FrameLayout (vedi immagine in basso)

così, questo è uno screenshot con Frammento A.

Ora, vorrei quando si fa clic su un pulsante sinistro, per sostituire il frammento a con frammento B, o C, o ...

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

Come potete vedere nel mio xml, FRAGMENT_A è hardcoded.

Immagina di voler passare tra 6 diversi frammenti, che cosa devo fare? Metti tutti i miei 6 frammenti nell'XML, o c'è un modo per sostituire a livello di programma FRAGMENT_A con FRAGMENT_B, C, D, E, ecc.

Grazie mille per il tuo aiuto.

enter image description here

risposta

14

uso FragmentTransaction per sostituire frammenti.

È possibile eseguire la sostituzione di frammenti in modo programmatico.

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

add to back stack è facoltativo.

Problemi correlati