Outils pour utilisateurs

Outils du site


android:fragment

La classe Fragment

Construire

Ajouter / Supprimer avec XML

Ajout d'un fragment à une activité Avantage : simple à mettre en œuvre Inconvénient : impossible de supprimer le fragment. Dans le cas où on souhaite basculer d'un fragment vers l'autre, il est préférable d'implémenter FragmentManager source

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />
 
</LinearLayout>

L'activité implémente alors ce layout

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);
    }
}

Ajouter / Supprimer au runtime

Utilise FragmentManager

Principe

Utiliser le FragmentManager pour créer une FragmentTransaction

Séquence

  • bonne pratique : ajouter le fragment initial lors l'appel à onCreate() de l'activité
  • obligatoire : créer une vue qui servira de conteneur pour les fragments
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  • Ajouter le fragment
setContentView(R.layout.fragment_layout);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// Being restored from a previous state ? do nothing to avoir overlapping
    if (savedInstanceState != null)
        return;
// Create an instance of ExampleFragment
    HeadlinesFragment firstFragment = new HeadlinesFragment();
            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());
 
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
android/fragment.txt · Dernière modification: 2016/10/17 13:56 (modification externe)