• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Creating a Fragment
2
3trainingnavtop=true
4
5@jd:body
6
7<div id="tb-wrapper">
8  <div id="tb">
9
10    <h2>This lesson teaches you to</h2>
11<ol>
12  <li><a href="#Create">Create a Fragment Class</a></li>
13  <li><a href="#AddInLayout">Add a Fragment to an Activity using XML</a></li>
14</ol>
15
16    <h2>You should also read</h2>
17    <ul>
18      <li><a href="{@docRoot}guide/components/fragments.html">Fragments</a></li>
19    </ul>
20
21<h2>Try it out</h2>
22
23<div class="download-box">
24 <a href="http://developer.android.com/shareables/training/FragmentBasics.zip"
25class="button">Download the sample</a>
26 <p class="filename">FragmentBasics.zip</p>
27</div>
28
29  </div>
30</div>
31
32<p>You can think of a fragment as a modular section of an activity, which has its own lifecycle,
33receives its own input events, and which you can add or remove while the activity is running (sort
34of like a "sub activity" that you can reuse in different activities). This lesson shows how to
35extend the {@link android.support.v4.app.Fragment} class using the Support Library so your app
36remains compatible with devices running system versions as old as Android 1.6.</p>
37
38<p class="note"><strong>Note:</strong> If you decide for other reasons that the minimum
39API level your app requires is 11 or higher, you don't need to use the Support
40Library and can instead use the framework's built in {@link android.app.Fragment} class and related
41APIs. Just be aware that this lesson is focused on using the APIs from the Support Library, which
42use a specific package signature and sometimes slightly different API names than the versions
43included in the platform.</p>
44
45
46
47<h2 id="Create">Create a Fragment Class</h2>
48
49<p>To create a fragment, extend the {@link android.support.v4.app.Fragment} class, then override
50key lifecycle methods to insert your app logic, similar to the way you would with an {@link
51android.app.Activity} class.</p>
52
53<p>One difference when creating a {@link android.support.v4.app.Fragment} is that you must use the
54{@link android.support.v4.app.Fragment#onCreateView onCreateView()} callback to define the layout.
55In fact, this is the only callback you need in order to get a fragment running. For
56example, here's a simple fragment that specifies its own layout:</p>
57
58<pre>
59import android.os.Bundle;
60import android.support.v4.app.Fragment;
61import android.view.LayoutInflater;
62import android.view.ViewGroup;
63
64public class ArticleFragment extends Fragment {
65    &#64;Override
66    public View onCreateView(LayoutInflater inflater, ViewGroup container,
67        Bundle savedInstanceState) {
68        // Inflate the layout for this fragment
69        return inflater.inflate(R.layout.article_view, container, false);
70    }
71}
72</pre>
73
74<p>Just like an activity, a fragment should implement other lifecycle callbacks that allow you to
75manage its state as it is added or removed from the activity and as the activity transitions
76between its lifecycle states. For instance, when the activity's {@link
77android.app.Activity#onPause()} method is called, any fragments in the activity also receive a call
78to {@link android.support.v4.app.Fragment#onPause()}.</p>
79
80<p>More information about the fragment lifecycle and callback methods is available in the <a
81href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p>
82
83
84
85<h2 id="AddInLayout">Add a Fragment to an Activity using XML</h2>
86
87<p>While fragments are reusable, modular UI components, each instance of a {@link
88android.support.v4.app.Fragment} class must be associated with a parent {@link
89android.support.v4.app.FragmentActivity}. You can achieve this association by defining each
90fragment within your activity layout XML file.</p>
91
92<p class="note"><strong>Note:</strong> {@link android.support.v4.app.FragmentActivity} is a
93special activity provided in the Support Library to handle fragments on system versions older than
94API level 11. If the lowest system version you support is API level 11 or higher, then you can use a
95regular {@link android.app.Activity}.</p>
96
97<p>Here is an example layout file that adds two fragments to an activity when the device
98screen is considered "large" (specified by the <code>large</code> qualifier in the directory
99name).</p>
100
101<p><code>res/layout-large/news_articles.xml:</code></p>
102<pre>
103&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
104    android:orientation="horizontal"
105    android:layout_width="fill_parent"
106    android:layout_height="fill_parent">
107
108    &lt;fragment android:name="com.example.android.fragments.HeadlinesFragment"
109              android:id="@+id/headlines_fragment"
110              android:layout_weight="1"
111              android:layout_width="0dp"
112              android:layout_height="match_parent" />
113
114    &lt;fragment android:name="com.example.android.fragments.ArticleFragment"
115              android:id="@+id/article_fragment"
116              android:layout_weight="2"
117              android:layout_width="0dp"
118              android:layout_height="match_parent" />
119
120&lt;/LinearLayout>
121</pre>
122
123<p class="note"><strong>Tip:</strong> For more information about creating layouts for different
124screen sizes, read <a href="{@docRoot}training/multiscreen/screensizes.html">Supporting Different
125Screen Sizes</a>.</p>
126
127<p>Here's how an activity applies this layout:</p>
128
129<pre>
130import android.os.Bundle;
131import android.support.v4.app.FragmentActivity;
132
133public class MainActivity extends FragmentActivity {
134    &#64;Override
135    public void onCreate(Bundle savedInstanceState) {
136        super.onCreate(savedInstanceState);
137        setContentView(R.layout.news_articles);
138    }
139}
140</pre>
141
142
143<p class="note"><strong>Note:</strong> When you add a fragment to an activity layout by defining
144the fragment in the layout XML file, you <em>cannot</em> remove the fragment at runtime. If you plan
145to swap your fragments in and out during user interaction, you must add the fragment to the activity
146when the activity first starts, as shown in the next lesson.</p>
147
148
149
150