• 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="#CreateActivity">Create the Second Activity</a></li>
23  <li><a href="#DisplayMessage">Display the Message</a></li>
24</ol>
25
26
27</div>
28</div>
29
30
31
32<p>After completing the <a href="building-ui.html">previous lesson</a>, you have an app that
33shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some
34code to <code>MainActivity</code> that
35starts a new activity when the user clicks the Send button.</p>
36
37
38<h2 id="RespondToButton">Respond to the Send Button</h2>
39
40<ol>
41  <li>In the file <code>res/layout/activity_main.xml</code>, add the
42    <a href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>
43    attribute to the {@link android.widget.Button &lt;Button&gt;} element as
44    shown below:
45    <pre>&lt;Button
46      android:layout_width="wrap_content"
47      android:layout_height="wrap_content"
48      android:text="@string/button_send"
49      <b>android:onClick="sendMessage"</b> />
50    </pre>
51    <p>This attribute tells the system to call the <code>sendMessage()</code>
52      method in your activity whenever a user clicks on the button.</p>
53  </li>
54
55  <li>In the file <code>java/com.example.myfirstapp/MainActivity.java</code>,
56    add the <code>sendMessage()</code> method stub as shown below:
57
58    <pre>public class MainActivity extends AppCompatActivity {
59    &#64;Override
60    protected void onCreate(Bundle savedInstanceState) {
61        super.onCreate(savedInstanceState);
62        setContentView(R.layout.activity_main);
63    }
64
65    <b>/** Called when the user clicks the Send button */
66    public void sendMessage(View view) {
67        // Do something in response to button
68    }</b>
69}</pre>
70
71    <p>In order for the system to match this method to the method name given to <a
72      href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>,
73      the signature must be exactly as shown. Specifically, the method must:</p>
74
75    <ul>
76    <li>Be public</li>
77    <li>Have a void return value</li>
78    <li>Have a {@link android.view.View} as the only parameter (this will be the {@link
79    android.view.View} that was clicked)</li>
80    </ul>
81
82</li>
83</ol>
84
85<p>Next, you’ll fill in this method to read the contents of the text field and deliver that text to
86another activity.</p>
87
88<h2 id="BuildIntent">Build an Intent</h2>
89<p>An {@link android.content.Intent} is an object that provides runtime binding
90  between separate components (such as two activities). The
91  {@link android.content.Intent} represents an app’s "intent to do something."
92  You can use intents for a wide variety of tasks, but in this lesson, your intent
93  starts another activity.</p>
94
95<p>In <code>MainActivity.java</code>, add the code shown below to
96  <code>sendMessage()</code>:</p>
97
98<pre>public class MainActivity extends AppCompatActivity {
99    <b>public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";</b>
100    &#64;Override
101    protected void onCreate(Bundle savedInstanceState) {
102        super.onCreate(savedInstanceState);
103        setContentView(R.layout.activity_main);
104    }
105
106    /** Called when the user clicks the Send button */
107    public void sendMessage(View view) {
108        <b>Intent intent = new Intent(this, DisplayMessageActivity.class);
109        EditText editText = (EditText) findViewById(R.id.edit_message);
110        String message = editText.getText().toString();
111        intent.putExtra(EXTRA_MESSAGE, message);
112        startActivity(intent);</b>
113    }
114}</pre>
115
116<p class="note"><strong>Note: </strong>Android Studio will display
117  <code>Cannot resolve symbol</code> errors because the code references classes
118  like {@link android.content.Intent} and {@link android.widget.EditText}
119  that have not been imported. To import these classes, you can either 1)
120  use Android Studio's "import class" functionality by pressing Alt + Enter
121  (Option + Return on Mac) or 2) manually add import statements at the top of
122  the file.</p>
123
124<p>There’s a lot going on in <code>sendMessage()</code>, so let’s explain
125  what's going on.</p>
126
127<p>The {@link android.content.Intent} constructor takes two parameters:</p>
128<ul>
129  <li>A {@link android.content.Context} as its first parameter ({@code this}
130    is used because the {@link android.app.Activity} class is a subclass of
131    {@link android.content.Context})
132  <li>The {@link java.lang.Class} of the app component to which the system
133    should deliver the {@link android.content.Intent} (in this case, the
134    activity that should be started).
135    <p class="note"><strong>Note:</strong> The reference to
136      <code>DisplayMessageActivity</code> will raise an error in Android Studio
137      because the class doesn’t exist yet. Ignore the error for now; you’ll
138      create the class soon.</p>
139</ul>
140
141<p>The {@link android.content.Intent#putExtra(String, String) putExtra()}
142  method adds the <code>EditText</code>'s value to the intent. An <code>Intent</code>
143  can carry data types as key-value pairs called <em>extras</em>. Your key is a
144  public constant <code>EXTRA_MESSAGE</code> because the next
145  activity uses the key to retrive the text value. It's a good practice to
146  define keys for intent extras using your app's package name as a prefix. This
147  ensures the keys are unique, in case your app interacts with other apps.</p>
148
149<p>The {@link android.app.Activity#startActivity(Intent) startActivity()}
150  method starts an instance of the <code>DisplayMessageActivity</code> specified
151  by the {@link android.content.Intent}. Now you need to create the class.</p>
152
153<h2 id="CreateActivity">Create the Second Activity</h2>
154
155<ol>
156  <li>In the <b>Project</b> window, right-click the <b>app</b> folder and select
157    <strong>New > Activity > Empty Activity</strong>.</li>
158  <li>In the <strong>Configure Activity</strong> window, enter
159    "DisplayMessageActivity" for <strong>Activity Name</strong> and click
160    <strong>Finish</strong>
161  </li>
162</ol>
163
164<p>Android Studio automatically does three things:</p>
165<ul>
166  <li>Creates the class <code>DisplayMessageActivity.java</code> with an
167   implementation of the required {@link android.app.Activity#onCreate(Bundle) onCreate()}
168    method.</li>
169  <li>Creates the corresponding layout file <code>activity_display_message.xml</code>
170    </li>
171  <li>Adds the required
172    <a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a>
173    element in <code>AndroidManifest.xml</code>.
174</ul>
175
176<p>If you run the app and click the Send button on the first activity, the
177  second activity starts but is empty. This is because the second activity uses
178  the default empty layout provided by the template.</p>
179
180<h2 id="DisplayMessage">Display the Message</h2>
181<p>Now you will modify the second activity to display the message that was passed
182by the first activity.</p>
183
184<ol>
185  <li>In {@code DisplayMessageActivity.java}, add the following code to the
186    <code>onCreate()</code> method:
187    <pre>&#64;Override
188protected void onCreate(Bundle savedInstanceState) {
189   super.onCreate(savedInstanceState);
190   setContentView(R.layout.activity_display_message);
191
192   Intent intent = getIntent();
193   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
194   TextView textView = new TextView(this);
195   textView.setTextSize(40);
196   textView.setText(message);
197
198   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
199   layout.addView(textView);
200}</pre>
201  </li>
202  <li>Press Alt + Enter (option + return on Mac) to import missing classes.</li>
203</ol>
204
205<p>There’s a lot going on here, so let’s explain:</p>
206
207<ol>
208  <li>The call {@link android.app.Activity#getIntent()} grabs the intent
209    that started the activity. Every {@link android.app.Activity} is invoked by an
210    {@link android.content.Intent}, regardless of how the user navigated there.
211    The call {@link android.content.Intent#getStringExtra(String) getStringExtra()}
212    retrieves the data from the first activity.</li>
213  <li>You programmatically create a {@link android.widget.TextView} and set
214    its size and message.
215  </li>
216  <li>You add the <code>TextView</code> to the layout identified by
217    {@code R.id.activity_display_message}. You cast the layout to
218    {@link android.view.ViewGroup} because it is the superclass of all layouts and
219    contains the {@link android.view.ViewGroup#addView(View) addView()}
220    method.</li>
221</ol>
222
223<p class="note"><strong>Note: </strong>The XML layout generated by previous
224  versions of Android Studio might not include the <code>android:id</code>
225  attribute. The call <code>findViewById()</code> will fail if the layout
226  does not have the <code>android:id</code> attribute. If this is the case,
227  open <code>activity_display_message.xml</code> and add the attribute
228  <code>android:id="@+id/activity_display_message"</code> to the layout element.
229</p>
230
231<p>You can now run the app. When it opens, type a message in the text field, and click
232<strong>Send</strong>. The second activity replaces the first one on the screen, showing
233the message you entered in the first activity.</p>
234
235<p>That's it, you've built your first Android app!</p>
236
237<p>To learn more, follow the link below to the next class.</p>