1page.title=Starting Another Activity 2parent.title=Building Your First App 3parent.link=index.html 4 5trainingnavtop=true 6previous.title=Building a Simpler User Interface 7previous.link=building-ui.html 8 9@jd:body 10 11 12<!-- This is the training bar --> 13<div id="tb-wrapper"> 14<div id="tb"> 15 16<h2>This lesson teaches you to</h2> 17 18<ol> 19 <li><a href="#RespondToButton">Respond to the Send Button</a></li> 20 <li><a href="#BuildIntent">Build an Intent</a></li> 21 <li><a href="#StartActivity">Start the Second Activity</a></li> 22 <li><a href="#CreateActivity">Create the Second Activity</a> 23 <ol> 24 <li><a href="#AddToManifest">Add it to the manifest</a></li> 25 </ol> 26 </li> 27 <li><a href="#ReceiveIntent">Receive the Intent</a></li> 28 <li><a href="#DisplayMessage">Display the Message</a></li> 29</ol> 30 31<h2>You should also read</h2> 32 33<ul> 34 <li><a href="{@docRoot}sdk/installing/index.html">Installing the 35SDK</a></li> 36</ul> 37 38 39</div> 40</div> 41 42 43 44<p>After completing the <a href="building-ui.html">previous lesson</a>, you have an app that 45shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some 46code to <code>MyFirstActivity</code> that 47starts a new activity when the user selects the Send button.</p> 48 49 50<h2 id="RespondToButton">Respond to the Send Button</h2> 51 52<p>To respond to the button's on-click event, open the <code>main.xml</code> layout file and add the 53<a 54href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a> 55attribute to the {@link android.widget.Button <Button>} element:</p> 56 57<pre> 58<Button 59 android:layout_width="wrap_content" 60 android:layout_height="wrap_content" 61 android:text="@string/button_send" 62 android:onClick="sendMessage" /> 63</pre> 64 65<p>The <a 66href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code 67android:onClick}</a> attribute’s value, <code>sendMessage</code>, is the name of a method in your 68activity that you want to call when the user selects the button.</p> 69 70<p>Add the corresponding method inside the <code>MyFirstActivity</code> class:</p> 71 72<pre> 73/** Called when the user selects the Send button */ 74public void sendMessage(View view) { 75 // Do something in response to button 76} 77</pre> 78 79<p class="note"><strong>Tip:</strong> In Eclipse, press Ctrl + Shift + O to import missing classes 80(Cmd + Shift + O on Mac).</p> 81 82<p>Note that, in order for the system to match this method to the method name given to <a 83href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>, 84the signature must be exactly as shown. Specifically, the method must:</p> 85 86<ul> 87<li>Be public</li> 88<li>Have a void return value</li> 89<li>Have a {@link android.view.View} as the only parameter (this will be the {@link 90android.view.View} that was clicked)</li> 91</ul> 92 93<p>Next, you’ll fill in this method to read the contents of the text field and deliver that text to 94another activity.</p> 95 96 97 98<h2 id="BuildIntent">Build an Intent</h2> 99 100<p>An {@link android.content.Intent} is an object that provides runtime binding between separate 101components (such as two activities). The {@link android.content.Intent} represents an 102app’s "intent to do something." You can use an {@link android.content.Intent} for a wide 103variety of tasks, but most often they’re used to start another activity.</p> 104 105<p>Inside the {@code sendMessage()} method, create an {@link android.content.Intent} to start 106an activity called {@code DisplayMessageActvity}:</p> 107 108<pre> 109Intent intent = new Intent(this, DisplayMessageActivity.class); 110</pre> 111 112<p>The constructor used here takes two parameters:</p> 113<ul> 114 <li>A {@link 115android.content.Context} as its first parameter ({@code this} is used because the {@link 116android.app.Activity} class is a subclass of {@link android.content.Context}) 117 <li>The {@link java.lang.Class} of the app component to which the system should deliver 118the {@link android.content.Intent} (in this case, the activity that should be started) 119</ul> 120 121<div class="sidebox-wrapper"> 122<div class="sidebox"> 123 <h3>Sending an intent to other apps</h3> 124 <p>The intent created in this lesson is what's considered an <em>explicit intent</em>, because the 125{@link android.content.Intent} 126specifies the exact app component to which the intent should be given. However, intents 127can also be <em>implicit</em>, in which case the {@link android.content.Intent} does not specify 128the desired component, but allows any app installed on the device to respond to the intent 129as long as it satisfies the meta-data specifications for the action that's specified in various 130{@link android.content.Intent} parameters. For more informations, see the class about <a 131href="{@docRoot}training/basics/intents/index.html">Interacting with Other Apps</a>.</p> 132</div> 133</div> 134 135<p class="note"><strong>Note:</strong> The reference to {@code DisplayMessageActivity} 136will raise an error if you’re using an IDE such as Eclipse because the class doesn’t exist yet. 137Ignore the error for now; you’ll create the class soon.</p> 138 139<p>An intent not only allows you to start another activity, but can carry a bundle of data to the 140activity as well. So, use {@link android.app.Activity#findViewById findViewById()} to get the 141{@link android.widget.EditText} element and add its message to the intent:</p> 142 143<pre> 144Intent intent = new Intent(this, DisplayMessageActivity.class); 145EditText editText = (EditText) findViewById(R.id.edit_message); 146String message = editText.getText().toString(); 147intent.putExtra(EXTRA_MESSAGE, message); 148</pre> 149 150<p>An {@link android.content.Intent} can carry a collection of various data types as key-value 151pairs called <em>extras</em>. The {@link android.content.Intent#putExtra putExtra()} method takes a 152string as the key and the value in the second parameter.</p> 153 154<p>In order for the next activity to query the extra data, you should define your keys using a 155public constant. So add the {@code EXTRA_MESSAGE} definition to the top of the {@code 156MyFirstActivity} class:</p> 157 158<pre> 159public class MyFirstActivity extends Activity { 160 public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE"; 161 ... 162} 163</pre> 164 165<p>It's generally a good practice to define keys for extras with your app's package name as a prefix 166to ensure it's unique, in case your app interacts with other apps.</p> 167 168 169<h2 id="StartActivity">Start the Second Activity</h2> 170 171<p>To start an activity, you simply need to call {@link android.app.Activity#startActivity 172startActivity()} and pass it your {@link android.content.Intent}.</p> 173 174<p>The system receives this call and starts an instance of the {@link android.app.Activity} 175specified by the {@link android.content.Intent}.</p> 176 177<p>With this method included, the complete {@code sendMessage()} method that's invoked by the Send 178button now looks like this:</p> 179 180<pre> 181/** Called when the user selects the Send button */ 182public void sendMessage(View view) { 183 Intent intent = new Intent(this, DisplayMessageActivity.class); 184 EditText editText = (EditText) findViewById(R.id.edit_message); 185 String message = editText.getText().toString(); 186 intent.putExtra(EXTRA_MESSAGE, message); 187 startActivity(intent); 188} 189</pre> 190 191<p>Now you need to create the {@code DisplayMessageActivity} class in order for this to 192work.</p> 193 194 195 196<h2 id="CreateActivity">Create the Second Activity</h2> 197 198<p>In your project, create a new class file under the <code>src/<package-name>/</code> 199directory called <code>DisplayMessageActivity.java</code>.</p> 200 201<p class="note"><strong>Tip:</strong> In Eclipse, right-click the package name under the 202<code>src/</code> directory and select <strong>New > Class</strong>. 203Enter "DisplayMessageActivity" for the name and {@code android.app.Activity} for the superclass.</p> 204 205<p>Inside the class, add the {@link android.app.Activity#onCreate onCreate()} callback method:</p> 206 207<pre> 208public class DisplayMessageActivity extends Activity { 209 @Override 210 public void onCreate(Bundle savedInstanceState) { 211 super.onCreate(savedInstanceState); 212 } 213} 214</pre> 215 216<p>All subclasses of {@link android.app.Activity} must implement the {@link 217android.app.Activity#onCreate onCreate()} method. The system calls this when creating a new 218instance of the activity. It is where you must define the activity layout and where you should 219initialize essential activity components.</p> 220 221 222 223<h3 id="AddToManifest">Add it to the manifest</h3> 224 225<p>You must declare all activities in your manifest file, <code>AndroidManifest.xml</code>, using an 226<a 227href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element.</p> 228 229<p>Because {@code DisplayMessageActivity} is invoked using an explicit intent, it does not require 230any intent filters (such as those you can see in the manifest for <code>MyFirstActivity</code>). So 231the declaration for <code>DisplayMessageActivity</code> can be simply one line of code inside the <a 232href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> 233element:</p> 234 235<pre> 236<application ... > 237 <activity android:name="com.example.myapp.DisplayMessageActivity" /> 238 ... 239</application> 240</pre> 241 242<p>The app is now runnable because the {@link android.content.Intent} in the 243first activity now resolves to the {@code DisplayMessageActivity} class. If you run the app now, 244pressing the Send button starts the 245second activity, but it doesn't show anything yet.</p> 246 247 248<h2 id="ReceiveIntent">Receive the Intent</h2> 249 250<p>Every {@link android.app.Activity} is invoked by an {@link android.content.Intent}, regardless of 251how the user navigated there. You can get the {@link android.content.Intent} that started your 252activity by calling {@link android.app.Activity#getIntent()} and the retrieve data contained 253within it.</p> 254 255<p>In the {@code DisplayMessageActivity} class’s {@link android.app.Activity#onCreate onCreate()} 256method, get the intent and extract the message delivered by {@code MyFirstActivity}:</p> 257 258<pre> 259Intent intent = getIntent(); 260String message = intent.getStringExtra(MyFirstActivity.EXTRA_MESSAGE); 261</pre> 262 263 264 265<h2 id="DisplayMessage">Display the Message</h2> 266 267<p>To show the message on the screen, create a {@link android.widget.TextView} widget and set the 268text using {@link android.widget.TextView#setText setText()}. Then add the {@link 269android.widget.TextView} as the root view of the activity’s layout by passing it to {@link 270android.app.Activity#setContentView setContentView()}.</p> 271 272<p>The complete {@link android.app.Activity#onCreate onCreate()} method for {@code 273DisplayMessageActivity} now looks like this:</p> 274 275<pre> 276@Override 277public void onCreate(Bundle savedInstanceState) { 278 super.onCreate(savedInstanceState); 279 280 // Get the message from the intent 281 Intent intent = getIntent(); 282 String message = intent.getStringExtra(MyFirstActivity.EXTRA_MESSAGE); 283 284 // Create the text view 285 TextView textView = new TextView(this); 286 textView.setTextSize(40); 287 textView.setText(message); 288 289 setContentView(textView); 290} 291</pre> 292 293<p>You can now run the app, type a message in the text field, press Send, and view the message on 294the second activity.</p> 295 296<img src="{@docRoot}images/training/firstapp/firstapp.png" /> 297<p class="img-caption"><strong>Figure 1.</strong> Both activities in the final app, running 298on Android 4.0. 299 300<p>That's it, you've built your first Android app!</p> 301 302<p>To learn more about building Android apps, continue to follow the 303basic training classes. The next class is <a 304href="{@docRoot}training/basics/activity-lifecycle/index.html">Managing the Activity 305Lifecycle</a>.</p> 306 307 308 309 310