Skip to content

Commit 67e988e

Browse files
scottamainAndroid (Google) Code Review
authored andcommitted
Merge "docs: for AU basic training on fragments including ZIP for sample app" into ics-mr1
2 parents 6ea11c0 + d9ee0d7 commit 67e988e

File tree

13 files changed

+1538
-0
lines changed

13 files changed

+1538
-0
lines changed
Binary file not shown.
Binary file not shown.

docs/html/images/training/basics/fragments-screen-mock.graffle/data.plist

Lines changed: 848 additions & 0 deletions
Large diffs are not rendered by default.
27.5 KB
Loading
12.2 KB
Loading
54.6 KB
Loading
97.6 KB
Loading
277 KB
Binary file not shown.
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
page.title=Communicating with Other Fragments
2+
parent.title=Building a Dynamic UI with Fragments
3+
parent.link=index.html
4+
5+
trainingnavtop=true
6+
previous.title=Building a Flexible UI
7+
previous.link=fragment-ui.html
8+
9+
@jd:body
10+
11+
<div id="tb-wrapper">
12+
<div id="tb">
13+
<h2>This lesson teaches you to</h2>
14+
<ol>
15+
<li><a href="#DefineInterface">Define an Interface</a></li>
16+
<li><a href="#Implement">Implement the Interface</a></li>
17+
<li><a href="#Deliver">Deliver a Message to a Fragment</a></li>
18+
</ol>
19+
20+
<h2>You should also read</h2>
21+
<ul>
22+
<li><a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a></li>
23+
</ul>
24+
25+
<h2>Try it out</h2>
26+
27+
<div class="download-box">
28+
<a href="http://developer.android.com/shareables/training/FragmentBasics.zip"
29+
class="button">Download the sample</a>
30+
<p class="filename">FragmentBasics.zip</p>
31+
</div>
32+
33+
</div>
34+
</div>
35+
36+
<p>In order to reuse the Fragment UI components, you should build each as a completely
37+
self-contained, modular component that defines its own layout and behavior. Once you
38+
have defined these reusable Fragments, you can associate them with an Activity and
39+
connect them with the application logic to realize the overall composite UI.</p>
40+
41+
<p>Often you will want one Fragment to communicate with another, for example to change
42+
the content based on a user event. All Fragment-to-Fragment communication is done
43+
through the associated Activity. Two Fragments should never communicate directly.</p>
44+
45+
46+
<h2 id="DefineInterface">Define an Interface</h2>
47+
48+
<p>To allow a Fragment to communicate up to its Activity, you can define an interface
49+
in the Fragment class and implement it within the Activity. The Fragment captures
50+
the interface implementation during its onAttach() lifecycle method and can then call
51+
the Interface methods in order to communicate with the Activity.</p>
52+
53+
<p>Here is an example of Fragment to Activity communication:</p>
54+
55+
<pre>
56+
public class HeadlinesFragment extends ListFragment {
57+
OnHeadlineSelectedListener mCallback;
58+
59+
// Container Activity must implement this interface
60+
public interface OnHeadlineSelectedListener {
61+
public void onArticleSelected(int position);
62+
}
63+
64+
&#64;Override
65+
public void onAttach(Activity activity) {
66+
super.onAttach(activity);
67+
68+
// This makes sure that the container activity has implemented
69+
// the callback interface. If not, it throws an exception
70+
try {
71+
mCallback = (OnHeadlineSelectedListener) activity;
72+
} catch (ClassCastException e) {
73+
throw new ClassCastException(activity.toString()
74+
+ " must implement OnHeadlineSelectedListener");
75+
}
76+
}
77+
78+
...
79+
}
80+
</pre>
81+
82+
<p>Now the fragment can deliver messages to the activity by calling the {@code
83+
onArticleSelected()} method (or other methods in the interface) using the {@code mCallback}
84+
instance of the {@code OnHeadlineSelectedListener} interface.</p>
85+
86+
<p>For example, the following method in the fragment is called when the user clicks on a list
87+
item. The fragment uses the callback interface to deliver the event to the parent activity.</p>
88+
89+
<pre>
90+
&#64;Override
91+
public void onListItemClick(ListView l, View v, int position, long id) {
92+
// Send the event to the host activity
93+
mCallback.onArticleSelected(position);
94+
}
95+
</pre>
96+
97+
98+
99+
<h2 id="Implement">Implement the Interface</h2>
100+
101+
<p>In order to receive event callbacks from the fragment, the activity that hosts it must
102+
implement the interface defined in the fragment class.</p>
103+
104+
<p>For example, the following activity implements the interface from the above example.</p>
105+
106+
<pre>
107+
public static class MainActivity extends Activity
108+
implements HeadlinesFragment.OnHeadlineSelectedListener{
109+
...
110+
111+
public void onArticleSelected(Uri articleUri) {
112+
// The user selected the headline of an article from the HeadlinesFragment
113+
// Do something here to display that article
114+
}
115+
}
116+
</pre>
117+
118+
119+
120+
<h2 id="Deliver">Deliver a Message to a Fragment</h2>
121+
122+
<p>The host activity can deliver messages to a fragment by capturing the {@link
123+
android.support.v4.app.Fragment} instance
124+
with {@link android.support.v4.app.FragmentManager#findFragmentById findFragmentById()}, then
125+
directly call the fragment's public methods.</p>
126+
127+
<p>For instance, imagine that the activity shown above may contain another fragment that's used to
128+
display the item specified by the data returned in the above callback method. In this case,
129+
the activity can pass the information received in the callback method to the other fragment that
130+
will display the item:</p>
131+
132+
<pre>
133+
public static class MainActivity extends Activity
134+
implements HeadlinesFragment.OnHeadlineSelectedListener{
135+
...
136+
137+
public void onArticleSelected(int position) {
138+
// The user selected the headline of an article from the HeadlinesFragment
139+
// Do something here to display that article
140+
141+
ArticleFragment articleFrag = (ArticleFragment)
142+
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
143+
144+
if (articleFrag != null) {
145+
// If article frag is available, we're in two-pane layout...
146+
147+
// Call a method in the ArticleFragment to update its content
148+
articleFrag.updateArticleView(position);
149+
} else {
150+
// Otherwise, we're in the one-pane layout and must swap frags...
151+
152+
// Create fragment and give it an argument for the selected article
153+
ArticleFragment newFragment = new ArticleFragment();
154+
Bundle args = new Bundle();
155+
args.putInt(ArticleFragment.ARG_POSITION, position);
156+
newFragment.setArguments(args);
157+
158+
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
159+
160+
// Replace whatever is in the fragment_container view with this fragment,
161+
// and add the transaction to the back stack so the user can navigate back
162+
transaction.replace(R.id.fragment_container, newFragment);
163+
transaction.addToBackStack(null);
164+
165+
// Commit the transaction
166+
transaction.commit();
167+
}
168+
}
169+
}
170+
</pre>
171+
172+
173+
174+
175+
176+
177+
178+
179+
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
page.title=Creating a Fragment
2+
parent.title=Building a Dynamic UI with Fragments
3+
parent.link=index.html
4+
5+
trainingnavtop=true
6+
previous.title=Using the Android Support Library
7+
previous.link=support-lib.html
8+
next.title=Building a Flexible UI
9+
next.link=fragment-ui.html
10+
11+
@jd:body
12+
13+
<div id="tb-wrapper">
14+
<div id="tb">
15+
16+
<h2>This lesson teaches you to</h2>
17+
<ol>
18+
<li><a href="#Create">Create a Fragment Class</a></li>
19+
<li><a href="#AddInLayout">Add a Fragment to an Activity using XML</a></li>
20+
</ol>
21+
22+
<h2>You should also read</h2>
23+
<ul>
24+
<li><a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a></li>
25+
</ul>
26+
27+
<h2>Try it out</h2>
28+
29+
<div class="download-box">
30+
<a href="http://developer.android.com/shareables/training/FragmentBasics.zip"
31+
class="button">Download the sample</a>
32+
<p class="filename">FragmentBasics.zip</p>
33+
</div>
34+
35+
</div>
36+
</div>
37+
38+
<p>You can think of a fragment as a modular section of an activity, which has its own lifecycle,
39+
receives its own input events, and which you can add or remove while the activity is running (sort
40+
of like a "sub activity" that you can reuse in different activities). This lesson shows how to
41+
extend the {@link android.support.v4.app.Fragment} class using the Support Library so your app
42+
remains compatible with devices running system versions as old as Android 1.6.</p>
43+
44+
<p class="note"><strong>Note:</strong> If you decide for other reasons that the minimum
45+
API level your app requires is 11 or higher, you don't need to use the Support
46+
Library and can instead use the framework's built in {@link android.app.Fragment} class and related
47+
APIs. Just be aware that this lesson is focused on using the APIs from the Support Library, which
48+
use a specific package signature and sometimes slightly different API names than the versions
49+
included in the platform.</p>
50+
51+
52+
53+
<h2 id="Create">Create a Fragment Class</h2>
54+
55+
<p>To create a fragment, extend the {@link android.support.v4.app.Fragment} class, then override
56+
key lifecycle methods to insert your app logic, similar to the way you would with an {@link
57+
android.app.Activity} class.</p>
58+
59+
<p>One difference when creating a {@link android.support.v4.app.Fragment} is that you must use the
60+
{@link android.support.v4.app.Fragment#onCreateView onCreateView()} callback to define the layout.
61+
In fact, this is the only callback you need in order to get a fragment running. For
62+
example, here's a simple fragment that specifies its own layout:</p>
63+
64+
<pre>
65+
import android.os.Bundle;
66+
import android.support.v4.app.Fragment;
67+
import android.view.LayoutInflater;
68+
import android.view.ViewGroup;
69+
70+
public class ArticleFragment extends Fragment {
71+
&#64;Override
72+
public View onCreateView(LayoutInflater inflater, ViewGroup container,
73+
Bundle savedInstanceState) {
74+
// Inflate the layout for this fragment
75+
return inflater.inflate(R.layout.article_view, container, false);
76+
}
77+
}
78+
</pre>
79+
80+
<p>Just like an activity, a fragment should implement other lifecycle callbacks that allow you to
81+
manage its state as it is added or removed from the activity and as the activity transitions
82+
between its lifecycle states. For instance, when the activity's {@link
83+
android.app.Activity#onPause()} method is called, any fragments in the activity also receive a call
84+
to {@link android.support.v4.app.Fragment#onPause()}.</p>
85+
86+
<p>More information about the fragment lifecycle and callback methods is available in the <a
87+
href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p>
88+
89+
90+
91+
<h2 id="AddInLayout">Add a Fragment to an Activity using XML</h2>
92+
93+
<p>While fragments are reusable, modular UI components, each instance of a {@link
94+
android.support.v4.app.Fragment} class must be associated with a parent {@link
95+
android.support.v4.app.FragmentActivity}. You can achieve this association by defining each
96+
fragment within your activity layout XML file.</p>
97+
98+
<p class="note"><strong>Note:</strong> {@link android.support.v4.app.FragmentActivity} is a
99+
special activity provided in the Support Library to handle fragments on system versions older than
100+
API level 11. If the lowest system version you support is API level 11 or higher, then you can use a
101+
regular {@link android.app.Activity}.</p>
102+
103+
<p>Here is an example layout file that adds two fragments to an activity when the device
104+
screen is considered "large" (specified by the <code>large</code> qualifier in the directory
105+
name).</p>
106+
107+
<p><code>res/layout-large/news_articles.xml:</code></p>
108+
<pre>
109+
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
110+
android:orientation="horizontal"
111+
android:layout_width="fill_parent"
112+
android:layout_height="fill_parent">
113+
114+
&lt;fragment android:name="com.example.android.fragments.HeadlinesFragment"
115+
android:id="@+id/headlines_fragment"
116+
android:layout_weight="1"
117+
android:layout_width="0dp"
118+
android:layout_height="match_parent" />
119+
120+
&lt;fragment android:name="com.example.android.fragments.ArticleFragment"
121+
android:id="@+id/article_fragment"
122+
android:layout_weight="2"
123+
android:layout_width="0dp"
124+
android:layout_height="match_parent" />
125+
126+
&lt;/LinearLayout>
127+
</pre>
128+
129+
<p class="note"><strong>Tip:</strong> For more information about creating layouts for different
130+
screen sizes, read <a href="{@docRoot}training/multiscreen/screensizes.html">Supporting Different
131+
Screen Sizes</a>.</p>
132+
133+
<p>Here's how an activity applies this layout:</p>
134+
135+
<pre>
136+
import android.os.Bundle;
137+
import android.support.v4.app.FragmentActivity;
138+
139+
public class MainActivity extends FragmentActivity {
140+
&#64;Override
141+
public void onCreate(Bundle savedInstanceState) {
142+
super.onCreate(savedInstanceState);
143+
setContentView(R.layout.news_articles);
144+
}
145+
}
146+
</pre>
147+
148+
149+
<p class="note"><strong>Note:</strong> When you add a fragment to an activity layout by defining
150+
the fragment in the layout XML file, you <em>cannot</em> remove the fragment at runtime. If you plan
151+
to swap your fragments in and out during user interaction, you must add the fragment to the activity
152+
when the activity first starts, as shown in the next lesson.</p>
153+
154+
155+

0 commit comments

Comments
 (0)