Recherche…


Remarques

Les fragments sont des composants très importants de l'interface utilisateur dans les applications Android. Ils ont été introduits en premier dans l'API Android 3.0 (Honeycomb).


Comprendre le paradigme de conception des fragments

Des fragments ont été introduits pour prendre en charge principalement une interface utilisateur modulaire et flexible sur les appareils à grand écran tels que les tablettes.

Les fragments sont gérés par une activité. Chaque fragment représente généralement une partie d'un écran. Il peut y avoir plus d'un fragment dans une activité. Les fragments peuvent aussi être appelés sous-activités . Lorsque vous ajoutez un fragment dans la disposition de votre activité, il se trouve dans un ViewGroup à l'intérieur de la hiérarchie de vues de l'activité et le fragment définit sa propre disposition de vue.


CYCLE DE LA VIE

Tout comme les activités, les fragments ont également un cycle de vie. Un fragment est notifié pour les événements suivants.

  1. Attachez- vous à l'activité - onAttach (Activity)
  2. Créer un fragment - onCreate (Bundle)
  3. Créer une vue - onCreateView (LayoutInflater, ViewGroup, Bundle)
  4. Création d'activité - onActivityCreated (Bundle)
  5. Etat de la vue restauré - onViewStateRestored (Bundle)
  6. Rendre visible à l'utilisateur - onStart ()
  7. début de l'interaction utilisateur - onResume ()
  8. pause de l'interaction de l'utilisateur - onPause ()
  9. Rendu invisible à l'utilisateur - onStop ()
  10. Destruction de vue - onDestroyView ()
  11. Détruire le fragment - onDestroy ()
  12. Se détacher d'une activité - onDetach ()

En tant que programmeur, vous devez remplacer diverses méthodes de rappel du cycle de vie, en général, nous implémentons les méthodes onCreate (), onCreateView () et onPause ().


Sous-classes de fragment

  1. DialogFragment - Pour afficher la boîte de dialogue flottante
  2. ListFragment - Pour afficher la liste des éléments
  3. PreferenceFragment - Utile pour créer une activité de paramètres

Les références

  1. https://developer.android.com/guide/components/fragments.html
  2. https://developer.android.com/reference/android/app/Fragment.html

Ajouter des fragments

Ajouter un fragment de manière statique

Fichier: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
  
    <fragment  
        android:id="@+id/fragment2"  
        android:name="com.example.fragmentexample.Fragment2"  
        android:layout_width="0px"  
        android:layout_height="match_parent"   
        android:layout_weight="1"  
        />  
  
    <fragment  
        android:id="@+id/fragment1"  
        android:name="com.example.fragmentexample.Fragment1"  
        android:layout_width="0px"  
        android:layout_height="match_parent"  
        android:layout_weight="1"  
         />  
  
</LinearLayout>  

Fichier: fragment1.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:background="#00ff00"  
     >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="fragment frist"  
        android:textAppearance="?android:attr/textAppearanceLarge" />  
  
</LinearLayout>  

Fichier: fragment2.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
    android:background="#0000ff"  
     >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Second Fragment"  
        android:textAppearance="?android:attr/textAppearanceLarge" />  
  
</LinearLayout>

Fichier: MainActivity.java

package com.example.fragmentexample;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
    }  
}  

Fichier: Fragment1.java

package com.example.fragmentexample;  
  
import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
  
public class Fragment1 extends Fragment {  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        return inflater.inflate(R.layout.fragment1,container, false);  
    }  
  
}  

Fichier: Fragment2.java

package com.example.fragmentexample;  
  
import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
  
public class Fragment2 extends Fragment {  
      
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        return inflater.inflate(R.layout.fragment2,container, false);  
    }  
  
}  

Ajout dynamique d'un fragment

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
  
    <FrameLayout  
        android:id="@+id/container1"   
        android:layout_width="0px"  
        android:layout_height="match_parent"   
        android:layout_weight="1"  
        />  
  
    <FrameLayout  
        android:id="@+id/container2"   
        android:layout_width="0px"  
        android:layout_height="match_parent"  
        android:layout_weight="1"  
         />  
  
</LinearLayout>

FrameLayout agit comme un conteneur de fragments.

Classe MainActivity

Fichier: MainActivity.java

package com.example.fragmentexample;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        loadFragment(this, R.id.container1,new Fragment1(),"fragment1");
        loadFragment(this, R.id.container2,new Fragment2(),"fragment2");    
    }  

    public static void loadFragment(Activity activity, int containerId, Fragment fragment, String tag)
    {
        activity.getSupportFragmentManager().beginTransaction().
            replace(containerId, fragment,tag).commitAllowingStateLoss();
    }
}  


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow