17

Supponiamo che io sono parecchi frammenti:frammento placehoder nel layout

public class FirstFragment extends Fragment { ... } 

public class SecondFragment extends Fragment { ... } 

public class ThirdFragment extends Fragment { ... } 

Ho anche un principale un'attività, il suo contenuto è (main.xml):

<LinearLayout ...> 

    <!-- How to have a fragment placehold without specify which fragment show here? --> 
    <fragment> 

</LinearLayout> 

La mia domanda è, in sopra il file di layout, come posso definire un segnaposto frammento senza specificare quale frammento mostrare qui, e quindi in My Activity java code, gonfiare un frammento appropriato per il segnaposto?

E 'possibile e come si fa?

risposta

31

È possibile. Nella tua main.xml, definire un segnaposto per il frammento, chiamiamolo "fragment_placeholder":

<LinearLayout ...> 
<FrameLayout android:id="@+id/fragment_placeholder" android:layout_weight="1" 
     android:layout_width="0px" 
     android:layout_height="match_parent" /> 
</LinearLayout> 

Nella vostra attività, ogni volta che si desidera caricare il frammento:

YourFragment fragment = new YourFragment(); 
FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.fragment_placeholder, fragment); 
ft.commit(); 
+1

ft.replace (...) dovrebbe essere cambiato in ft.add (...) nel mio caso. –

+0

yes, and android: layout_width deve essere impostato su wrap_content – Markus

+0

Vedi questo per maggiori informazioni: http://developer.android.com/training/basics/fragments/fragment-ui.html – Hardy

Problemi correlati