• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Starting Another Activity
2parent.title=Building Your First App
3parent.link=index.html
4
5trainingnavtop=true
6
7page.tags=intents
8helpoutsWidget=true
9
10@jd:body
11
12
13<!-- This is the training bar -->
14<div id="tb-wrapper">
15<div id="tb">
16
17<h2>This lesson teaches you to</h2>
18
19<ol>
20  <li><a href="#RespondToButton">Respond to the Send Button</a></li>
21  <li><a href="#BuildIntent">Build an Intent</a></li>
22  <!-- <li><a href="#StartActivity">Start the Second Activity</a></li> -->
23  <li><a href="#CreateActivity">Create the Second Activity</a></li>
24  <li><a href="#ReceiveIntent">Receive the Intent</a></li>
25  <li><a href="#DisplayMessage">Display the Message</a></li>
26</ol>
27
28
29</div>
30</div>
31
32
33
34<p>After completing the <a href="building-ui.html">previous lesson</a>, you have an app that
35shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some
36code to <code>MyActivity</code> that
37starts a new activity when the user clicks the Send button.</p>
38
39
40<h2 id="RespondToButton">Respond to the Send Button</h2>
41
42<ol>
43<li>In Android Studio, from the <code>res/layout</code> directory, edit the <code>content_my.xml</code>
44file.</li>
45<li>Add the <a
46href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>
47attribute to the {@link android.widget.Button &lt;Button&gt;} element.
48
49<p class="code-caption">res/layout/content_my.xml</p>
50<pre>
51&lt;Button
52    android:layout_width="wrap_content"
53    android:layout_height="wrap_content"
54    android:text="@string/button_send"
55    android:onClick="sendMessage" />
56</pre>
57
58<p>The <a
59href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code
60android:onClick}</a> attribute’s value, <code>"sendMessage"</code>, is the name of a method in your
61activity that the system calls when the user clicks the button.</p>
62</li>
63<li>In the <code>java/com.mycompany.myfirstapp</code> directory, open the <code>MyActivity.java</code> file.</li>
64<li>Within the <code>MyActivity</code> class, add the {@code sendMessage()} method stub shown
65below.
66
67<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
68<pre>
69/** Called when the user clicks the Send button */
70public void sendMessage(View view) {
71    // Do something in response to button
72}
73</pre>
74
75<p>In order for the system to match this method to the method name given to <a
76href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>,
77the signature must be exactly as shown. Specifically, the method must:</p>
78
79<ul>
80<li>Be public</li>
81<li>Have a void return value</li>
82<li>Have a {@link android.view.View} as the only parameter (this will be the {@link
83android.view.View} that was clicked)</li>
84</ul>
85
86</li>
87</ol>
88
89<p>Next, you’ll fill in this method to read the contents of the text field and deliver that text to
90another activity.</p>
91
92<h2 id="BuildIntent">Build an Intent</h2>
93
94<ol>
95<li>In <code>MyActivity.java</code>, inside the {@code sendMessage()} method, create an
96{@link android.content.Intent} to start an activity called {@code DisplayMessageActivity} with the
97following code:
98
99<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
100<pre>
101public void sendMessage(View view) {
102  Intent intent = new Intent(this, DisplayMessageActivity.class);
103}
104</pre>
105
106<div class="sidebox-wrapper">
107<div class="sidebox">
108<h3>Intents</h3>
109<p>An {@link android.content.Intent} is an object that provides runtime binding between separate
110components (such as two activities). The {@link android.content.Intent} represents an
111app’s "intent to do something." You can use intents for a wide
112variety of tasks, but most often they’re used to start another activity. For more information, see
113<a href="{@docRoot}guide/components/intents-filters.html ">Intents and Intent Filters</a>.</p>
114</div>
115</div>
116
117<p class="note"><strong>Note:</strong> The reference to {@code DisplayMessageActivity}
118will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet.
119Ignore the error for now; you’ll create the class soon.</p>
120
121<p>The constructor used here takes two parameters:</p>
122<ul>
123  <li>A {@link
124android.content.Context} as its first parameter ({@code this} is used because the {@link
125android.app.Activity} class is a subclass of {@link android.content.Context})
126  <li>The {@link java.lang.Class} of the app component to which the system should deliver
127the {@link android.content.Intent} (in this case, the activity that should be started)
128</ul>
129
130<p>Android Studio indicates that you must import the {@link android.content.Intent} class.</p>
131
132</li>
133<li>At the top of the file, import the {@link android.content.Intent} class:
134<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
135<pre>
136import android.content.Intent;
137</pre>
138<p class="note"><strong>Tip:</strong> In Android Studio, press Alt + Enter (option + return on Mac)
139  to import missing classes.</p>
140</li>
141
142<!-- I didn't think this was necessary
143<div class="sidebox-wrapper">
144<div class="sidebox">
145  <h3>Sending an intent to other apps</h3>
146  <p>The intent created in this lesson is what's considered an <em>explicit intent</em>, because the
147{@link android.content.Intent}
148specifies the exact app component to which the intent should be given. However, intents
149can also be <em>implicit</em>, in which case the {@link android.content.Intent} does not specify
150the desired component, but allows any app installed on the device to respond to the intent
151as long as it satisfies the meta-data specifications for the action that's specified in various
152{@link android.content.Intent} parameters. For more information, see the class about <a
153href="{@docRoot}training/basics/intents/index.html">Interacting with Other Apps</a>.</p>
154</div>
155</div>
156-->
157
158<li>Inside the {@code sendMessage()} method,
159use {@link android.app.Activity#findViewById findViewById()} to get the
160{@link android.widget.EditText} element.
161<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
162<pre>
163public void sendMessage(View view) {
164  Intent intent = new Intent(this, DisplayMessageActivity.class);
165  EditText editText = (EditText) findViewById(R.id.edit_message);
166}
167</pre>
168</li>
169
170<li>At the top of the file, import the {@link android.widget.EditText} class.
171  <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p>
172</li>
173
174<li>Assign the text to a local <code>message</code> variable, and use the
175{@link android.content.Intent#putExtra putExtra()} method to add its text value to the intent.
176<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
177<pre>
178public void sendMessage(View view) {
179  Intent intent = new Intent(this, DisplayMessageActivity.class);
180  EditText editText = (EditText) findViewById(R.id.edit_message);
181  String message = editText.getText().toString();
182  intent.putExtra(EXTRA_MESSAGE, message);
183}
184</pre>
185
186<p>An {@link android.content.Intent} can carry data types as key-value
187pairs called <em>extras</em>. The {@link android.content.Intent#putExtra putExtra()} method takes the
188key name in the first parameter and the value in the second parameter.</p>
189
190</li>
191<li>At the top of the {@code MyActivity} class, add the {@code EXTRA_MESSAGE} definition as
192follows:
193<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
194<pre>
195public class MyActivity extends AppCompatActivity {
196    public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
197    ...
198}
199</pre>
200
201<p>For the next activity to query the extra data, you should define the key
202for your intent's extra using a public constant. It's generally a good practice to define keys for
203intent extras using your app's package name as a prefix. This ensures the keys are unique, in case
204your app interacts with other apps.</p>
205
206</li>
207
208<!-- <h2 id="StartActivity">Start the Second Activity</h2> -->
209
210<li>In the {@code sendMessage()} method, to finish the intent, call the
211{@link android.app.Activity#startActivity startActivity()} method, passing it the
212{@link android.content.Intent} object created in step 1.
213
214</ol>
215
216<p>With this new code, the complete {@code sendMessage()} method that's invoked by the Send
217button now looks like this:</p>
218<p class="code-caption">java/com.mycompany.myfirstapp/MyActivity.java</p>
219<pre>
220/** Called when the user clicks the Send button */
221public void sendMessage(View view) {
222    Intent intent = new Intent(this, DisplayMessageActivity.class);
223    EditText editText = (EditText) findViewById(R.id.edit_message);
224    String message = editText.getText().toString();
225    intent.putExtra(EXTRA_MESSAGE, message);
226    startActivity(intent);
227}
228</pre>
229
230<p>The system receives this call and starts an instance of the {@link android.app.Activity}
231specified by the {@link android.content.Intent}. Now you need to create the
232{@code DisplayMessageActivity} class in order for this to work.</p>
233
234</li>
235</ol>
236
237
238<h2 id="CreateActivity">Create the Second Activity</h2>
239
240<p>All subclasses of {@link android.app.Activity} must implement the
241{@link android.app.Activity#onCreate onCreate()} method. This method is where the activity receives
242the intent with the message, then renders the message. Also, the
243{@link android.app.Activity#onCreate onCreate()} method must define the activity
244layout with the {@link android.app.Activity#setContentView setContentView()} method. This is where
245the activity performs the initial setup of the activity components.</p>
246
247<h3>Create a new activity using Android Studio</h3>
248
249<p>Android Studio includes a stub for the
250{@link android.app.Activity#onCreate onCreate()} method when you create a new activity. The
251<em>New Android Activity</em> window appears.</p>
252
253<ol>
254  <li>In Android Studio, in the <code>java</code> directory, select the package,
255    <strong>com.mycompany.myfirstapp</strong>, right-click, and select
256    <strong>New > Activity > Blank Activity</strong>.</li>
257  <li>In the <strong>Choose options</strong> window, fill in the activity details:
258    <ul>
259      <li><strong>Activity Name</strong>: DisplayMessageActivity</li>
260      <li><strong>Layout Name</strong>: activity_display_message</li>
261      <li><strong>Title</strong>: My Message</li>
262      <li><strong>Hierarchical Parent</strong>: com.mycompany.myfirstapp.MyActivity</li>
263      <li><strong>Package name</strong>: com.mycompany.myfirstapp</li>
264    </ul>
265    <p>Click <strong>Finish</strong>.</p>
266  </li>
267
268<li>Open the {@code DisplayMessageActivity.java} file.
269
270<p>The class already includes an implementation of the required
271{@link android.app.Activity#onCreate onCreate()} method. You update the implementation of this
272method later.</p>
273
274<!-- Android Studio does not create a Fragment placeholder
275<p>Also, the file includes a <code>PlaceholderFragment</code> class that extends
276{@link android.app.Fragment}. This activity does not implement fragments, but you might use this
277later in the training. Fragments decompose application functionality and UI into reusable modules.
278For more information on fragments, see the
279<a href="{@docRoot}guide/components/fragments.html">Fragments API Guide</a> and follow the training,
280<a href="{@docRoot}training/basics/fragments/index.html">Building A Dynamic UI with Fragments</a>.
281</p>
282-->
283</li>
284</ol>
285
286<!-- Not needed for Android Studio
287<p class="note"><strong>Note:</strong> Your activity may look different if you did not use
288the latest version of the ADT plugin. Make sure you install the latest version of the
289<a href="{@docRoot}tools/sdk/eclipse-adt.html">ADT plugin</a> to complete this tutorial.</p>
290-->
291
292<p>If you're developing with Android Studio, you can run the app now, but not much happens.
293Clicking the Send button starts the second activity, but it uses
294a default "Hello world" layout provided by the template. You'll soon update the
295activity to instead display a custom text view.</p>
296
297
298<h3>Create the activity without Android Studio</h3>
299
300<p>If you're using a different IDE or the command line tools, do the following:</p>
301
302<ol>
303<li>Create a new file named {@code DisplayMessageActivity.java} in the project's <code>src/</code>
304directory, next to the original {@code MyActivity.java} file.</li>
305<li>Add the following code to the file:
306
307<pre>
308public class DisplayMessageActivity extends AppCompatActivity {
309
310    &#64;Override
311    protected void onCreate(Bundle savedInstanceState) {
312        super.onCreate(savedInstanceState);
313        setContentView(R.layout.activity_display_message);
314
315        if (savedInstanceState == null) {
316            getSupportFragmentManager().beginTransaction()
317                .add(R.id.container, new PlaceholderFragment()).commit();
318        }
319    }
320
321    &#64;Override
322    public boolean onOptionsItemSelected(MenuItem item) {
323        // Handle app bar item clicks here. The app bar
324        // automatically handles clicks on the Home/Up button, so long
325        // as you specify a parent activity in AndroidManifest.xml.
326        int id = item.getItemId();
327        if (id == R.id.action_settings) {
328            return true;
329        }
330        return super.onOptionsItemSelected(item);
331    }
332
333    /**
334     * A placeholder fragment containing a simple view.
335     */
336    public static class PlaceholderFragment extends Fragment {
337
338        public PlaceholderFragment() { }
339
340        &#64;Override
341        public View onCreateView(LayoutInflater inflater, ViewGroup container,
342                  Bundle savedInstanceState) {
343              View rootView = inflater.inflate(R.layout.fragment_display_message,
344                      container, false);
345              return rootView;
346        }
347    }
348}
349</pre>
350
351<p class="note"><strong>Note:</strong> If you are using an IDE other than Android Studio, your project
352does not contain the {@code activity_display_message} layout that's requested by
353{@link android.app.Activity#setContentView setContentView()}. That's OK because
354you will update this method later and won't be using that layout.</p>
355
356</li>
357
358<li>To your {@code strings.xml} file, add the new activity's title as follows:
359<pre>
360&lt;resources>
361    ...
362    &lt;string name="title_activity_display_message">My Message&lt;/string>
363&lt;/resources>
364</pre>
365</li>
366
367<li>In your manifest file, <code>AndroidManifest.xml</code>, within the <code>Application</code>
368element, add the
369<a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element
370for your {@code DisplayMessageActivity} class, as follows:
371
372<pre>
373&lt;application ... >
374    ...
375    &lt;activity
376        android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
377        android:label="@string/title_activity_display_message"
378        android:parentActivityName="com.mycompany.myfirstapp.MyActivity" >
379        &lt;meta-data
380            android:name="android.support.PARENT_ACTIVITY"
381            android:value="com.mycompany.myfirstapp.MyActivity" />
382    &lt;/activity>
383&lt;/application>
384</pre>
385
386</li>
387</ol>
388
389<p>The <a href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code
390android:parentActivityName}</a> attribute declares the name of this activity's parent activity
391within the app's logical hierarchy. The system uses this value
392to implement default navigation behaviors, such as <a
393href="{@docRoot}design/patterns/navigation.html">Up navigation</a> on
394Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for
395older versions of Android by using the
396<a href="{@docRoot}tools/support-library/index.html">Support Library</a> and adding
397the <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
398<meta-data>}</a> element as shown here.</p>
399
400<p class="note"><strong>Note:</strong> Your Android SDK should already include
401the latest Android Support Library, which you installed during the
402<a href="{@docRoot}studio/intro/update.html">Adding SDK Packages</a> step.
403When using the templates in Android Studio, the Support Library is automatically added to your app project
404(you can see the library's JAR file listed under <em>Android Dependencies</em>). If you're not using
405Android Studio, you need to manually add the library to your project&mdash;follow the guide for <a
406href="{@docRoot}tools/support-library/setup.html">setting up the Support Library</a>
407then return here.</p>
408
409<p>If you're using a different IDE than Android Studio, don't worry that the app won't yet compile.
410You'll soon update the activity to display a custom text view.</p>
411
412
413<h2 id="ReceiveIntent">Receive the Intent</h2>
414
415<p>Every {@link android.app.Activity} is invoked by an {@link android.content.Intent}, regardless of
416how the user navigated there. You can get the {@link android.content.Intent} that started your
417activity by calling {@link android.app.Activity#getIntent()} and retrieve the data contained
418within the intent.</p>
419
420<ol>
421<li>In the <code>java/com.mycompany.myfirstapp</code> directory, edit the
422  {@code DisplayMessageActivity.java} file.</li>
423<li>Get the intent and assign it to a local variable.
424<pre>
425Intent intent = getIntent();
426</pre>
427</li>
428<li>At the top of the file, import the {@link android.content.Intent} class.
429  <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p>
430</li>
431<li>Extract the message delivered by {@code MyActivity} with the
432{@link android.content.Intent#getStringExtra getStringExtra()} method.
433<pre>
434String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
435</pre>
436</li>
437</ol>
438
439<h2 id="DisplayMessage">Display the Message</h2>
440
441<ol>
442<li>In the res/layout directory, edit the {@code content_display_message.xml} file.</li>
443<li>Add an {@code android:id} attribute to the {@code RelativeLayout}.
444You need this attribute to reference the object from your app code.</li>
445
446<pre>
447&lt; RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
448...
449android:id="@+id/content"&gt;
450&lt;/RelativeLayout&gt;
451</pre>
452<li>Switch back to editing {@code DisplayMessageActivity.java}.</li>
453
454
455<li>In the {@link android.app.Activity#onCreate onCreate()} method, create a {@link android.widget.TextView} object.
456<pre>
457TextView textView = new TextView(this);
458</pre>
459</li>
460<li>Set the text size and message with {@link android.widget.TextView#setText setText()}.
461<pre>
462textView.setTextSize(40);
463textView.setText(message);
464</pre>
465</li>
466<li>Add the {@link android.widget.TextView} to the {@link android.widget.RelativeLayout}
467identified by {@code R.id.content}.
468<pre>
469RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
470layout.addView(textView);
471</pre>
472</li>
473<li>At the top of the file, import the {@link android.widget.TextView} class.
474  <p>In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.</p>
475</li>
476</ol>
477
478<p>The complete {@link android.app.Activity#onCreate onCreate()} method for {@code
479DisplayMessageActivity} now looks like this:</p>
480
481<pre>
482&#64;Override
483protected void onCreate(Bundle savedInstanceState) {
484   super.onCreate(savedInstanceState);
485   setContentView(R.layout.activity_display_message);
486   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
487   setSupportActionBar(toolbar);
488
489   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
490   fab.setOnClickListener(new View.OnClickListener() {
491       &#64;Override
492       public void onClick(View view) {
493           Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
494                   .setAction("Action", null)
495                   .show();
496       }
497   });
498   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
499
500   Intent intent = getIntent();
501   String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
502   TextView textView = new TextView(this);
503   textView.setTextSize(40);
504   textView.setText(message);
505
506   RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
507   layout.addView(textView);
508</pre>
509
510<p>You can now run the app. When it opens, type a message in the text field, and click
511<strong>Send</strong>. The second activity replaces the first one on the screen, showing
512the message you entered in the first activity.</p>
513
514<p>That's it, you've built your first Android app!</p>
515
516<p>To learn more, follow the link below to the next class.</p>
517
518
519
520
521