Pourquoi utiliser des fragments ?

Support libraries

dependencies {
    ...
    compile "com.android.support:support-v4:18.0.+"
}
dependencies {
    ...
    compile "com.android.support:appcompat-v7:18.0.+"
}

Creation d’un fragment

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class DetailFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        return inflater.inflate(R.layout.detail, container, false);
    }
}

Ajouter un fragment à un layout

<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.ListFragment"
              android:id="@+id/listFragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />
    <fragment android:name="com.example.DetailFragment"
              android:id="@+id/detailFragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />
</LinearLayout>

Ajouter un fragment à un layout

UI responsive

Fragments

Placeholders

Pour gérer différemment le cas un ou deux blocs

Et le code ?

if (findViewById(R.id.second_fragment) != null) {
    DetailFragment detailFragment = new DetailFragment();
    getSupportFragmentManager()
        .beginTransaction()
            .add(R.id.second_fragment, detailFragment)
            .commit();
}