• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Fragments
2parent.title=Activities
3parent.link=activities.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8  <h2>In this document</h2>
9  <ol>
10    <li><a href="#Design">Design Philosophy</a></li>
11    <li><a href="#Creating">Creating a Fragment</a>
12      <ol>
13        <li><a href="#UI">Adding a user interface</a></li>
14        <li><a href="#Adding">Adding a fragment to an activity</a></li>
15      </ol>
16    </li>
17    <li><a href="#Managing">Managing Fragments</a></li>
18    <li><a href="#Transactions">Performing Fragment Transactions</a></li>
19    <li><a href="#CommunicatingWithActivity">Communicating with the Activity</a>
20      <ol>
21        <li><a href="#EventCallbacks">Creating event callbacks to the activity</a></li>
22        <li><a href="#ActionBar">Adding items to the Action Bar</a></li>
23      </ol>
24    </li>
25    <li><a href="#Lifecycle">Handling the Fragment Lifecycle</a>
26      <ol>
27        <li><a href="#CoordinatingWithActivity">Coordinating with the activity lifecycle</a></li>
28      </ol>
29    </li>
30    <li><a href="#Example">Example</a></li>
31  </ol>
32
33  <h2>Key classes</h2>
34  <ol>
35    <li>{@link android.app.Fragment}</li>
36    <li>{@link android.app.FragmentManager}</li>
37    <li>{@link android.app.FragmentTransaction}</li>
38  </ol>
39
40  <h2>See also</h2>
41  <ol>
42    <li><a href="{@docRoot}training/basics/fragments/index.html">Building a Dynamic UI with Fragments</a></li>
43    <li><a href="{@docRoot}guide/practices/tablets-and-handsets.html">Supporting Tablets
44and Handsets</a></li>
45  </ol>
46</div>
47</div>
48
49<p>A {@link android.app.Fragment} represents a behavior or a portion of user interface in an
50{@link android.app.Activity}. You can combine multiple fragments in a single activity to build a
51multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a
52modular section of an activity, which has its own lifecycle, receives its own input events, and
53which you can add or remove while the activity is running (sort of like a "sub activity" that
54you can reuse in different activities).</p>
55
56<p>A fragment must always be embedded in an activity and the fragment's lifecycle is directly
57affected by the host activity's lifecycle. For example, when the activity is paused, so are all
58fragments in it, and when the activity is destroyed, so are all fragments. However, while an
59activity is running (it is in the <em>resumed</em> <a
60href="{@docRoot}guide/components/activities.html#Lifecycle">lifecycle state</a>), you can
61manipulate each fragment independently, such as add or remove them. When you perform such a
62fragment transaction, you can also add it to a back stack that's managed by the
63activity&mdash;each back stack entry in the activity is a record of the fragment transaction that
64occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards),
65by pressing the <em>Back</em> button.</p>
66
67<p>When you add a fragment as a part of your activity layout, it lives in a {@link
68android.view.ViewGroup} inside the activity's view hierarchy and the fragment defines its own view
69layout.
70You can insert a fragment into your activity layout by declaring the fragment in the activity's
71layout file, as a {@code &lt;fragment&gt;} element, or from your application code by adding it to an
72existing {@link android.view.ViewGroup}. However, a fragment is not required to be a part of the
73activity layout; you may also use a fragment without its own UI as an invisible worker for the
74activity.</p>
75
76<p>This document describes how to build your application to use fragments, including
77how fragments can maintain their state when added to the activity's back stack, share
78events with the activity and other fragments in the activity, contribute to the activity's action
79bar, and more.</p>
80
81
82<h2 id="Design">Design Philosophy</h2>
83
84<p>Android introduced fragments in Android 3.0 (API level 11), primarily to support more
85dynamic and flexible UI designs on large screens, such as tablets. Because a
86tablet's screen is much larger than that of a handset, there's more room to combine and
87interchange UI components. Fragments allow such designs without the need for you to manage complex
88changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able
89to modify the activity's appearance at runtime and preserve those changes in a back stack
90that's managed by the activity.</p>
91
92<p>For example, a news application can use one fragment to show a list of articles on the
93left and another fragment to display an article on the right&mdash;both fragments appear in one
94activity, side by side, and each fragment has its own set of lifecycle callback methods and handle
95their own user input events. Thus, instead of using one activity to select an article and another
96activity to read the article, the user can select an article and read it all within the same
97activity, as illustrated in the tablet layout in figure 1.</p>
98
99<p>You should design each fragment as a modular and reusable activity component. That is, because
100each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can
101include one fragment in multiple activities, so you should design for reuse and avoid directly
102manipulating one fragment from another fragment. This is especially important because a modular
103fragment allows you to change your fragment combinations for different screen sizes. When designing
104your application to support both tablets and handsets, you can reuse your fragments in different
105layout configurations to optimize the user experience based on the available screen space. For
106example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when
107more than one cannot fit within the same activity.</p>
108
109<img src="{@docRoot}images/fundamentals/fragments.png" alt="" />
110<p class="img-caption"><strong>Figure 1.</strong> An example of how two UI modules defined by
111fragments can be combined into one activity for a tablet design, but separated for a
112handset design.</p>
113
114<p>For example&mdash;to continue with the news application example&mdash;the application can embed
115two fragments in <em>Activity A</em>, when running on a tablet-sized device. However, on a
116handset-sized screen, there's not enough room for both fragments, so <em>Activity A</em> includes
117only the fragment for the list of articles, and when the user selects an article, it starts
118<em>Activity B</em>, which includes the second fragment to read the article. Thus, the application
119supports both tablets and handsets by reusing fragments in different combinations, as illustrated in
120figure 1.</p>
121
122<p>For more information about designing your application with different fragment combinations for
123different screen configurations, see the guide to <a
124href="{@docRoot}guide/practices/tablets-and-handsets.html">Supporting Tablets and Handsets</a>.</p>
125
126
127
128<h2 id="Creating">Creating a Fragment</h2>
129
130<div class="figure" style="width:327px">
131<img src="{@docRoot}images/fragment_lifecycle.png" alt="" />
132<p class="img-caption"><strong>Figure 2.</strong> The lifecycle of a fragment (while its
133activity is running).</p>
134</div>
135
136<p>To create a fragment, you must create a subclass of {@link android.app.Fragment} (or an existing
137subclass of it). The {@link android.app.Fragment} class has code that looks a lot like
138an {@link android.app.Activity}. It contains callback methods similar to an activity, such
139as {@link android.app.Fragment#onCreate onCreate()}, {@link android.app.Fragment#onStart onStart()},
140{@link android.app.Fragment#onPause onPause()}, and {@link android.app.Fragment#onStop onStop()}. In
141fact, if you're converting an existing Android application to use fragments, you might simply move
142code from your activity's callback methods into the respective callback methods of your
143fragment.</p>
144
145<p>Usually, you should implement at least the following lifecycle methods:</p>
146
147<dl>
148  <dt>{@link android.app.Fragment#onCreate onCreate()}</dt>
149  <dd>The system calls this when creating the fragment. Within your implementation, you should
150initialize essential components of the fragment that you want to retain when the fragment is
151paused or stopped, then resumed.</dd>
152  <dt>{@link android.app.Fragment#onCreateView onCreateView()}</dt>
153  <dd>The system calls this when it's time for the fragment to draw its user interface for the
154first time. To draw a UI for your fragment, you must return a {@link android.view.View} from this
155method that is the root of your fragment's layout. You can return null if the fragment does not
156provide a UI.</dd>
157  <dt>{@link android.app.Activity#onPause onPause()}</dt>
158  <dd>The system calls this method as the first indication that the user is leaving the
159fragment (though it does not always mean the fragment is being destroyed). This is usually where you
160should commit any changes that should be persisted beyond the current user session (because
161the user might not come back).</dd>
162</dl>
163
164<p>Most applications should implement at least these three methods for every fragment, but there are
165several other callback methods you should also use to handle various stages of the
166fragment lifecycle. All the lifecycle callback methods are discussed in more detail in the section
167about <a href="#Lifecycle">Handling the Fragment Lifecycle</a>.</p>
168
169
170<p>There are also a few subclasses that you might want to extend, instead of the base {@link
171android.app.Fragment} class:</p>
172
173<dl>
174  <dt>{@link android.app.DialogFragment}</dt>
175  <dd>Displays a floating dialog. Using this class to create a dialog is a good alternative to using
176the dialog helper methods in the {@link android.app.Activity} class, because you can
177incorporate a fragment dialog into the back stack of fragments managed by the activity,
178allowing the user to return to a dismissed fragment.</dd>
179
180  <dt>{@link android.app.ListFragment}</dt>
181  <dd>Displays a list of items that are managed by an adapter (such as a {@link
182android.widget.SimpleCursorAdapter}), similar to {@link android.app.ListActivity}. It provides
183several methods for managing a list view, such as the {@link
184android.app.ListFragment#onListItemClick(ListView,View,int,long) onListItemClick()} callback to
185handle click events.</dd>
186
187  <dt>{@link android.preference.PreferenceFragment}</dt>
188  <dd>Displays a hierarchy of {@link android.preference.Preference} objects as a list, similar to
189{@link android.preference.PreferenceActivity}. This is useful when creating a "settings"
190activity for your application.</dd>
191</dl>
192
193
194<h3 id="UI">Adding a user interface</h3>
195
196<p>A fragment is usually used as part of an activity's user interface and contributes its own
197layout to the activity.</p>
198
199<p>To provide a layout for a fragment, you must implement the {@link
200android.app.Fragment#onCreateView onCreateView()} callback method, which the Android system calls
201when it's time for the fragment to draw its layout. Your implementation of this method must return a
202{@link android.view.View} that is the root of your fragment's layout.</p>
203
204<p class="note"><strong>Note:</strong> If your fragment is a subclass of {@link
205android.app.ListFragment}, the default implementation returns a {@link android.widget.ListView} from
206{@link android.app.Fragment#onCreateView onCreateView()}, so you don't need to implement it.</p>
207
208<p>To return a layout from {@link
209android.app.Fragment#onCreateView onCreateView()}, you can inflate it from a <a
210href="{@docRoot}guide/topics/resources/layout-resource.html">layout resource</a> defined in XML. To
211help you do so, {@link android.app.Fragment#onCreateView onCreateView()} provides a
212{@link android.view.LayoutInflater} object.</p>
213
214<p>For example, here's a subclass of {@link android.app.Fragment} that loads a layout from the
215{@code example_fragment.xml} file:</p>
216
217<pre>
218public static class ExampleFragment extends Fragment {
219    &#64;Override
220    public View onCreateView(LayoutInflater inflater, ViewGroup container,
221                             Bundle savedInstanceState) {
222        // Inflate the layout for this fragment
223        return inflater.inflate(R.layout.example_fragment, container, false);
224    }
225}
226</pre>
227
228<div class="sidebox-wrapper">
229<div class="sidebox">
230  <h3>Creating a layout</h3>
231  <p>In the sample above, {@code R.layout.example_fragment} is a reference to a layout resource
232named {@code example_fragment.xml} saved in the application resources. For information about how to
233create a layout in XML, see the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a>
234documentation.</p>
235</div>
236</div>
237
238<p>The {@code container} parameter passed to {@link android.app.Fragment#onCreateView
239onCreateView()} is the parent {@link android.view.ViewGroup} (from the activity's layout) in which
240your fragment layout
241will be inserted. The {@code savedInstanceState} parameter is a {@link android.os.Bundle} that
242provides data about the previous instance of the fragment, if the fragment is being resumed
243(restoring state is discussed more in the section about <a href="#Lifecycle">Handling the
244Fragment Lifecycle</a>).</p>
245
246<p>The {@link android.view.LayoutInflater#inflate(int,ViewGroup,boolean) inflate()} method takes
247three arguments:</p>
248<ul>
249  <li>The resource ID of the layout you want to inflate.</li>
250  <li>The {@link android.view.ViewGroup} to be the parent of the inflated layout. Passing the {@code
251container} is important in order for the system to apply layout parameters to the root view of the
252inflated layout, specified by the parent view in which it's going.</li>
253  <li>A boolean indicating whether the inflated layout should be attached to the {@link
254android.view.ViewGroup} (the second parameter) during inflation. (In this case, this
255is false because the system is already inserting the inflated layout into the {@code
256container}&mdash;passing true would create a redundant view group in the final layout.)</li>
257</ul>
258
259<p>Now you've seen how to create a fragment that provides a layout. Next, you need to add
260the fragment to your activity.</p>
261
262
263
264<h3 id="Adding">Adding a fragment to an activity</h3>
265
266<p>Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part
267of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity
268layout:</p>
269
270<ul>
271  <li><b>Declare the fragment inside the activity's layout file.</b>
272<p>In this case, you can
273specify layout properties for the fragment as if it were a view. For example, here's the layout
274file for an activity with two fragments:</p>
275<pre>
276&lt;?xml version="1.0" encoding="utf-8"?&gt;
277&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
278    android:orientation="horizontal"
279    android:layout_width="match_parent"
280    android:layout_height="match_parent"&gt;
281    &lt;fragment android:name="com.example.news.ArticleListFragment"
282            android:id="@+id/list"
283            android:layout_weight="1"
284            android:layout_width="0dp"
285            android:layout_height="match_parent" /&gt;
286    &lt;fragment android:name="com.example.news.ArticleReaderFragment"
287            android:id="@+id/viewer"
288            android:layout_weight="2"
289            android:layout_width="0dp"
290            android:layout_height="match_parent" /&gt;
291&lt;/LinearLayout&gt;
292</pre>
293  <p>The {@code android:name} attribute in the {@code &lt;fragment&gt;} specifies the {@link
294android.app.Fragment} class to instantiate in the layout.</p>
295
296<p>When the system creates this activity layout, it instantiates each fragment specified in the
297layout and calls the {@link android.app.Fragment#onCreateView onCreateView()} method for each one,
298to retrieve each fragment's layout. The system inserts the {@link android.view.View} returned by the
299fragment directly in place of the {@code &lt;fragment&gt;} element.</p>
300
301<div class="note">
302  <p><strong>Note:</strong> Each fragment requires a unique identifier that
303the system can use to restore the fragment if the activity is restarted (and which you can use to
304capture the fragment to perform transactions, such as remove it). There are three ways to provide an
305ID for a fragment:</p>
306  <ul>
307    <li>Supply the {@code android:id} attribute with a unique ID.</li>
308    <li>Supply the {@code android:tag} attribute with a unique string.</li>
309    <li>If you provide neither of the previous two, the system uses the ID of the container
310view.</li>
311  </ul>
312</div>
313  </li>
314
315  <li><b>Or, programmatically add the fragment to an existing {@link android.view.ViewGroup}.</b>
316<p>At any time while your activity is running, you can add fragments to your activity layout. You
317simply need to specify a {@link
318android.view.ViewGroup} in which to place the fragment.</p>
319  <p>To make fragment transactions in your activity (such as add, remove, or replace a
320fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance
321of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} like this:</p>
322
323<pre>
324FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()}
325FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
326</pre>
327
328<p>You can then add a fragment using the {@link
329android.app.FragmentTransaction#add(int,Fragment) add()} method, specifying the fragment to add and
330the view in which to insert it. For example:</p>
331
332<pre>
333ExampleFragment fragment = new ExampleFragment();
334fragmentTransaction.add(R.id.fragment_container, fragment);
335fragmentTransaction.commit();
336</pre>
337
338  <p>The first argument passed to {@link android.app.FragmentTransaction#add(int,Fragment) add()}
339is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by
340resource ID, and the second parameter is the fragment to add.</p>
341  <p>Once you've made your changes with
342{@link android.app.FragmentTransaction}, you must
343call {@link android.app.FragmentTransaction#commit} for the changes to take effect.</p>
344  </li>
345</ul>
346
347
348<h4 id="AddingWithoutUI">Adding a fragment without a UI</h4>
349
350<p>The examples above show how to add a fragment to your activity in order to provide a UI. However,
351you can also use a fragment to provide a background behavior for the activity without presenting
352additional UI.</p>
353
354<p>To add a fragment without a UI, add the fragment from the activity using {@link
355android.app.FragmentTransaction#add(Fragment,String)} (supplying a unique string "tag" for the
356fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a
357view in the activity layout, it does not receive a call to {@link
358android.app.Fragment#onCreateView onCreateView()}. So you don't need to implement that method.</p>
359
360<p>Supplying a string tag for the fragment isn't strictly for non-UI fragments&mdash;you can also
361supply string tags to fragments that do have a UI&mdash;but if the fragment does not have a
362UI, then the string tag is the only way to identify it. If you want to get the fragment from the
363activity later, you need to use {@link android.app.FragmentManager#findFragmentByTag
364findFragmentByTag()}.</p>
365
366<p>For an example activity that uses a fragment as a background worker, without a UI, see the {@code
367FragmentRetainInstance.java} sample, which is included in the SDK samples (available through the
368Android SDK Manager) and located on your system as
369<code>&lt;sdk_root&gt;/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java</code>.</p>
370
371
372
373<h2 id="Managing">Managing Fragments</h2>
374
375<p>To manage the fragments in your activity, you need to use {@link android.app.FragmentManager}. To
376get it, call {@link android.app.Activity#getFragmentManager()} from your activity.</p>
377
378<p>Some things that you can do with {@link android.app.FragmentManager} include:</p>
379
380<ul>
381  <li>Get fragments that exist in the activity, with {@link
382android.app.FragmentManager#findFragmentById findFragmentById()} (for fragments that provide a UI in
383the activity layout) or {@link android.app.FragmentManager#findFragmentByTag
384findFragmentByTag()} (for fragments that do or don't provide a UI).</li>
385  <li>Pop fragments off the back stack, with {@link
386android.app.FragmentManager#popBackStack()} (simulating a <em>Back</em> command by the user).</li>
387  <li>Register a listener for changes to the back stack, with {@link
388android.app.FragmentManager#addOnBackStackChangedListener addOnBackStackChangedListener()}.</li>
389</ul>
390
391<p>For more information about these methods and others, refer to the {@link
392android.app.FragmentManager} class documentation.</p>
393
394<p>As demonstrated in the previous section, you can also use {@link android.app.FragmentManager}
395to open a {@link android.app.FragmentTransaction}, which allows you to perform transactions, such as
396add and remove fragments.</p>
397
398
399<h2 id="Transactions">Performing Fragment Transactions</h2>
400
401<p>A great feature about using fragments in your activity is the ability to add, remove, replace,
402and perform other actions with them, in response to user interaction. Each set of changes that you
403commit to the activity is called a transaction and you can perform one using APIs in {@link
404android.app.FragmentTransaction}. You can also save each transaction to a back stack managed by the
405activity, allowing the user to navigate backward through the fragment changes (similar to navigating
406backward through activities).</p>
407
408<p>You can acquire an instance of {@link android.app.FragmentTransaction} from the {@link
409android.app.FragmentManager} like this:</p>
410
411<pre>
412FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()};
413FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
414</pre>
415
416<p>Each transaction is a set of changes that you want to perform at the same time. You can set
417up all the changes you want to perform for a given transaction using methods such as {@link
418android.app.FragmentTransaction#add add()}, {@link android.app.FragmentTransaction#remove remove()},
419and {@link android.app.FragmentTransaction#replace replace()}. Then, to apply the transaction
420to the activity, you must call {@link android.app.FragmentTransaction#commit()}.</p>
421</dl>
422
423<p>Before you call {@link
424android.app.FragmentTransaction#commit()}, however, you might want to call {@link
425android.app.FragmentTransaction#addToBackStack addToBackStack()}, in order to add the transaction
426to a back stack of fragment transactions. This back stack is managed by the activity and allows
427the user to return to the previous fragment state, by pressing the <em>Back</em> button.</p>
428
429<p>For example, here's how you can replace one fragment with another, and preserve the previous
430state in the back stack:</p>
431
432<pre>
433// Create new fragment and transaction
434Fragment newFragment = new ExampleFragment();
435FragmentTransaction transaction = getFragmentManager().beginTransaction();
436
437// Replace whatever is in the fragment_container view with this fragment,
438// and add the transaction to the back stack
439transaction.replace(R.id.fragment_container, newFragment);
440transaction.addToBackStack(null);
441
442// Commit the transaction
443transaction.commit();
444</pre>
445
446<p>In this example, {@code newFragment} replaces whatever fragment (if any) is currently in the
447layout container identified by the {@code R.id.fragment_container} ID. By calling {@link
448android.app.FragmentTransaction#addToBackStack addToBackStack()}, the replace transaction is
449saved to the back stack so the user can reverse the transaction and bring back the
450previous fragment by pressing the <em>Back</em> button.</p>
451
452<p>If you add multiple changes to the transaction (such as another {@link
453android.app.FragmentTransaction#add add()} or {@link android.app.FragmentTransaction#remove
454remove()}) and call {@link
455android.app.FragmentTransaction#addToBackStack addToBackStack()}, then all changes applied
456before you call {@link android.app.FragmentTransaction#commit commit()} are added to the
457back stack as a single transaction and the <em>Back</em> button will reverse them all together.</p>
458
459<p>The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter,
460except:</p>
461<ul>
462  <li>You must call {@link android.app.FragmentTransaction#commit()} last</li>
463  <li>If you're adding multiple fragments to the same container, then the order in which
464you add them determines the order they appear in the view hierarchy</li>
465</ul>
466
467<p>If you do not call {@link android.app.FragmentTransaction#addToBackStack(String)
468addToBackStack()} when you perform a transaction that removes a fragment, then that fragment is
469destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you
470do call {@link android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} when
471removing a fragment, then the fragment is <em>stopped</em> and will be resumed if the user navigates
472back.</p>
473
474<p class="note"><strong>Tip:</strong> For each fragment transaction, you can apply a transition
475animation, by calling {@link android.app.FragmentTransaction#setTransition setTransition()} before
476you commit.</p>
477
478<p>Calling {@link android.app.FragmentTransaction#commit()} does not perform the transaction
479immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon
480as the thread is able to do so. If necessary, however, you may call {@link
481android.app.FragmentManager#executePendingTransactions()} from your UI thread to immediately execute
482transactions submitted by {@link android.app.FragmentTransaction#commit()}. Doing so is
483usually not necessary unless the transaction is a dependency for jobs in other threads.</p>
484
485<p class="caution"><strong>Caution:</strong> You can commit a transaction using {@link
486android.app.FragmentTransaction#commit commit()} only prior to the activity <a
487href="{@docRoot}guide/components/activities.html#SavingActivityState">saving its
488state</a> (when the user leaves the activity). If you attempt to commit after that point, an
489exception will be thrown. This is because the state after the commit can be lost if the activity
490needs to be restored. For situations in which its okay that you lose the commit, use {@link
491android.app.FragmentTransaction#commitAllowingStateLoss()}.</p>
492
493
494
495
496<h2 id="CommunicatingWithActivity">Communicating with the Activity</h2>
497
498<p>Although a {@link android.app.Fragment} is implemented as an object that's independent from an
499{@link android.app.Activity} and can be used inside multiple activities, a given instance of
500a fragment is directly tied to the activity that contains it.</p>
501
502<p>Specifically, the fragment can access the {@link android.app.Activity} instance with {@link
503android.app.Fragment#getActivity()} and easily perform tasks such as find a view in the
504activity layout:</p>
505
506<pre>
507View listView = {@link android.app.Fragment#getActivity()}.{@link android.app.Activity#findViewById findViewById}(R.id.list);
508</pre>
509
510<p>Likewise, your activity can call methods in the fragment by acquiring a reference to the
511{@link android.app.Fragment} from {@link android.app.FragmentManager}, using {@link
512android.app.FragmentManager#findFragmentById findFragmentById()} or {@link
513android.app.FragmentManager#findFragmentByTag findFragmentByTag()}. For example:</p>
514
515<pre>
516ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
517</pre>
518
519
520<h3 id="EventCallbacks">Creating event callbacks to the activity</h3>
521
522<p>In some cases, you might need a fragment to share events with the activity. A good way to do that
523is to define a callback interface inside the fragment and require that the host activity implement
524it. When the activity receives a callback through the interface, it can share the information with
525other fragments in the layout as necessary.</p>
526
527<p>For example, if a news application has two fragments in an activity&mdash;one to show a list of
528articles (fragment A) and another to display an article (fragment B)&mdash;then fragment A must tell
529the activity when a list item is selected so that it can tell fragment B to display the article. In
530this case, the {@code OnArticleSelectedListener} interface is declared inside fragment A:</p>
531
532<pre>
533public static class FragmentA extends ListFragment {
534    ...
535    // Container Activity must implement this interface
536    public interface OnArticleSelectedListener {
537        public void onArticleSelected(Uri articleUri);
538    }
539    ...
540}
541</pre>
542
543<p>Then the activity that hosts the fragment implements the {@code OnArticleSelectedListener}
544interface and
545overrides {@code onArticleSelected()} to notify fragment B of the event from fragment A. To ensure
546that the host activity implements this interface, fragment A's {@link
547android.app.Fragment#onAttach onAttach()} callback method (which the system calls when adding
548the fragment to the activity) instantiates an instance of {@code OnArticleSelectedListener} by
549casting the {@link android.app.Activity} that is passed into {@link android.app.Fragment#onAttach
550onAttach()}:</p>
551
552<pre>
553public static class FragmentA extends ListFragment {
554    OnArticleSelectedListener mListener;
555    ...
556    &#64;Override
557    public void onAttach(Activity activity) {
558        super.onAttach(activity);
559        try {
560            mListener = (OnArticleSelectedListener) activity;
561        } catch (ClassCastException e) {
562            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
563        }
564    }
565    ...
566}
567</pre>
568
569<p>If the activity has not implemented the interface, then the fragment throws a
570{@link java.lang.ClassCastException}.
571On success, the {@code mListener} member holds a reference to activity's implementation of
572{@code OnArticleSelectedListener}, so that fragment A can share events with the activity by calling
573methods defined by the {@code OnArticleSelectedListener} interface. For example, if fragment A is an
574extension of {@link android.app.ListFragment}, each time
575the user clicks a list item, the system calls {@link android.app.ListFragment#onListItemClick
576onListItemClick()} in the fragment, which then calls {@code onArticleSelected()} to share
577the event with the activity:</p>
578
579<pre>
580public static class FragmentA extends ListFragment {
581    OnArticleSelectedListener mListener;
582    ...
583    &#64;Override
584    public void onListItemClick(ListView l, View v, int position, long id) {
585        // Append the clicked item's row ID with the content provider Uri
586        Uri noteUri = ContentUris.{@link android.content.ContentUris#withAppendedId withAppendedId}(ArticleColumns.CONTENT_URI, id);
587        // Send the event and Uri to the host activity
588        mListener.onArticleSelected(noteUri);
589    }
590    ...
591}
592</pre>
593
594<p>The {@code id} parameter passed to {@link
595android.app.ListFragment#onListItemClick onListItemClick()} is the row ID of the clicked item,
596which the activity (or other fragment) uses to fetch the article from the application's {@link
597android.content.ContentProvider}.</p>
598
599<p><!--To see a complete implementation of this kind of callback interface, see the <a
600href="{@docRoot}resources/samples/NotePad/index.html">NotePad sample</a>. -->More information about
601using a content provider is available in the <a
602href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> document.</p>
603
604
605
606<h3 id="ActionBar">Adding items to the Action Bar</h3>
607
608<p>Your fragments can contribute menu items to the activity's <a
609href="{@docRoot}guide/topics/ui/menus.html#options-menu">Options Menu</a> (and, consequently, the <a
610href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>) by implementing
611{@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. In order
612for this method to receive calls, however, you must call {@link
613android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} during {@link
614android.app.Fragment#onCreate(Bundle) onCreate()}, to indicate that the fragment
615would like to add items to the Options Menu (otherwise, the fragment will not receive a call to
616{@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()}).</p>
617
618<p>Any items that you then add to the Options Menu from the fragment are appended to the existing
619menu items. The fragment also receives callbacks to {@link
620android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} when a menu item
621is selected.</p>
622
623<p>You can also register a view in your fragment layout to provide a context menu by calling {@link
624android.app.Fragment#registerForContextMenu(View) registerForContextMenu()}. When the user opens
625the context menu, the fragment receives a call to {@link
626android.app.Fragment#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo)
627onCreateContextMenu()}. When the user selects an item, the fragment receives a call to {@link
628android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.</p>
629
630<p class="note"><strong>Note:</strong> Although your fragment receives an on-item-selected callback
631for each menu item it adds, the activity is first to receive the respective callback when the user
632selects a menu item. If the activity's implementation of the on-item-selected callback does not
633handle the selected item, then the event is passed to the fragment's callback. This is true for
634the Options Menu and context menus.</p>
635
636<p>For more information about menus, see the <a
637href="{@docRoot}guide/topics/ui/menus.html">Menus</a> and <a
638href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guides.</p>
639
640
641
642
643<h2 id="Lifecycle">Handling the Fragment Lifecycle</h2>
644
645<div class="figure" style="width:350px">
646<img src="{@docRoot}images/activity_fragment_lifecycle.png" alt=""/>
647<p class="img-caption"><strong>Figure 3.</strong> The effect of the activity lifecycle on the fragment
648lifecycle.</p>
649</div>
650
651<p>Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like
652an activity, a fragment can exist in three states:</p>
653
654<dl>
655  <dt><i>Resumed</i></dt>
656    <dd>The fragment is visible in the running activity.</dd>
657
658  <dt><i>Paused</i></dt>
659    <dd>Another activity is in the foreground and has focus, but the activity in which this
660fragment lives is still visible (the foreground activity is partially transparent or doesn't
661cover the entire screen).</dd>
662
663  <dt><i>Stopped</i></dt>
664    <dd>The fragment is not visible. Either the host activity has been stopped or the
665fragment has been removed from the activity but added to the back stack. A stopped fragment is
666still alive (all state and member information is retained by the system). However, it is no longer
667visible to the user and will be killed if the activity is killed.</dd>
668</dl>
669
670<p>Also like an activity, you can retain the state of a fragment using a {@link
671android.os.Bundle}, in case the activity's process is killed and you need to restore the
672fragment state when the activity is recreated. You can save the state during the fragment's {@link
673android.app.Fragment#onSaveInstanceState onSaveInstanceState()} callback and restore it during
674either {@link android.app.Fragment#onCreate onCreate()}, {@link
675android.app.Fragment#onCreateView onCreateView()}, or {@link
676android.app.Fragment#onActivityCreated onActivityCreated()}. For more information about saving
677state, see the <a
678href="{@docRoot}guide/components/activities.html#SavingActivityState">Activities</a>
679document.</p>
680
681<p>The most significant difference in lifecycle between an activity and a fragment is how one is
682stored in its respective back stack. An activity is placed into a back stack of activities
683that's managed by the system when it's stopped, by default (so that the user can navigate back
684to it with the <em>Back</em> button, as discussed in <a
685href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>).
686However, a fragment is placed into a back stack managed by the host activity only when you
687explicitly request that the instance be saved by calling {@link
688android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} during a transaction that
689removes the fragment.</p>
690
691<p>Otherwise, managing the fragment lifecycle is very similar to managing the activity
692lifecycle. So, the same practices for <a
693href="{@docRoot}guide/components/activities.html#Lifecycle">managing the activity
694lifecycle</a> also apply to fragments. What you also need to understand, though, is how the life
695of the activity affects the life of the fragment.</p>
696
697<p class="caution"><strong>Caution:</strong> If you need a {@link android.content.Context} object
698within your {@link android.app.Fragment}, you can call {@link android.app.Fragment#getActivity()}.
699However, be careful to call {@link android.app.Fragment#getActivity()} only when the fragment is
700attached to an activity. When the fragment is not yet attached, or was detached during the end of
701its lifecycle, {@link android.app.Fragment#getActivity()} will return null.</p>
702
703
704<h3 id="CoordinatingWithActivity">Coordinating with the activity lifecycle</h3>
705
706<p>The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the
707fragment, such that each lifecycle callback for the activity results in a similar callback for each
708fragment. For example, when the activity receives {@link android.app.Activity#onPause}, each
709fragment in the activity receives {@link android.app.Fragment#onPause}.</p>
710
711<p>Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the
712activity in order to perform actions such as build and destroy the fragment's UI. These additional
713callback methods are:</p>
714
715<dl>
716  <dt>{@link android.app.Fragment#onAttach onAttach()}</dt>
717    <dd>Called when the fragment has been associated with the activity (the {@link
718android.app.Activity} is passed in here).</dd>
719  <dt>{@link android.app.Fragment#onCreateView onCreateView()}</dt>
720    <dd>Called to create the view hierarchy associated with the fragment.</dd>
721  <dt>{@link android.app.Fragment#onActivityCreated onActivityCreated()}</dt>
722    <dd>Called when the activity's {@link android.app.Activity#onCreate
723onCreate()} method has returned.</dd>
724  <dt>{@link android.app.Fragment#onDestroyView onDestroyView()}</dt>
725    <dd>Called when the view hierarchy associated with the fragment is being removed.</dd>
726  <dt>{@link android.app.Fragment#onDetach onDetach()}</dt>
727    <dd>Called when the fragment is being disassociated from the activity.</dd>
728</dl>
729
730<p>The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated
731by figure 3. In this figure, you can see how each successive state of the activity determines which
732callback methods a fragment may receive. For example, when the activity has received its {@link
733android.app.Activity#onCreate onCreate()} callback, a fragment in the activity receives no more than
734the {@link android.app.Fragment#onActivityCreated onActivityCreated()} callback.</p>
735
736<p>Once the activity reaches the resumed state, you can freely add and remove fragments to the
737activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment
738change independently.</p>
739
740<p>However, when the activity leaves the resumed state, the fragment again is pushed through its
741lifecycle by the activity.</p>
742
743
744
745
746<h2 id="Example">Example</h2>
747
748<p>To bring everything discussed in this document together, here's an example of an activity
749using two fragments to create a two-pane layout. The activity below includes one fragment to
750show a list of Shakespeare play titles and another to show a summary of the play when selected
751from the list. It also demonstrates how to provide different configurations of the fragments,
752based on the screen configuration.</p>
753
754<p class="note"><strong>Note:</strong> The complete source code for this activity is available in
755<a
756href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.html">{@code
757FragmentLayout.java}</a>.</p>
758
759<p>The main activity applies a layout in the usual way, during {@link
760android.app.Activity#onCreate onCreate()}:</p>
761
762{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java main}
763
764<p>The layout applied is {@code fragment_layout.xml}:</p>
765
766{@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
767
768<p>Using this layout, the system instantiates the {@code TitlesFragment} (which lists the play
769titles) as soon as the activity loads the layout, while the {@link android.widget.FrameLayout}
770(where the fragment for showing the play summary will go) consumes space on the right side of the
771screen, but remains empty at first. As you'll see below, it's not until the user selects an item
772from the list that a fragment is placed into the {@link android.widget.FrameLayout}.</p>
773
774<p>However, not all screen configurations are wide enough to show both the list of
775plays and the summary, side by side. So, the layout above is used only for the landscape
776screen configuration, by saving it at {@code res/layout-land/fragment_layout.xml}.</p>
777
778<p>Thus, when the screen is in portrait orientation, the system applies the following layout, which
779is saved at {@code res/layout/fragment_layout.xml}:</p>
780
781{@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
782
783<p>This layout includes only {@code TitlesFragment}. This means that, when the device is in
784portrait orientation, only the list of play titles is visible. So, when the user clicks a list
785item in this configuration, the application will start a new activity to show the summary,
786instead of loading a second fragment.</p>
787
788<p>Next, you can see how this is accomplished in the fragment classes. First is {@code
789TitlesFragment}, which shows the list of Shakespeare play titles. This fragment extends {@link
790android.app.ListFragment} and relies on it to handle most of the list view work.</p>
791
792<p>As you inspect this code, notice that there are two possible behaviors when the user clicks a
793list item: depending on which of the two layouts is active, it can either create and display a new
794fragment to show the details in the same activity (adding the fragment to the {@link
795android.widget.FrameLayout}), or start a new activity (where the fragment can be shown).</p>
796
797{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java titles}
798
799<p>The second fragment, {@code DetailsFragment} shows the play summary for the item selected from
800the list from {@code TitlesFragment}:</p>
801
802{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details}
803
804<p>Recall from the {@code TitlesFragment} class, that, if the user clicks a list item and the
805current layout does <em>not</em> include the {@code R.id.details} view (which is where the
806{@code DetailsFragment} belongs), then the application starts the {@code DetailsActivity}
807activity to display the content of the item.</p>
808
809<p>Here is the {@code DetailsActivity}, which simply embeds the {@code DetailsFragment} to display
810the selected play summary when the screen is in portrait orientation:</p>
811
812{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
813details_activity}
814
815<p>Notice that this activity finishes itself if the configuration is landscape, so that the main
816activity can take over and display the {@code DetailsFragment} alongside the {@code TitlesFragment}.
817This can happen if the user begins the {@code DetailsActivity} while in portrait orientation, but
818then rotates to landscape (which restarts the current activity).</p>
819
820
821<p>For more samples using fragments (and complete source files for this example),
822see the API Demos sample app available in <a
823href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment">
824ApiDemos</a> (available for download from the <a
825href="{@docRoot}resources/samples/get.html">Samples SDK component</a>).</p>
826
827
828