1 page.title=Starting Another Activity 2 parent.title=Building Your First App 3 parent.link=index.html 4 5 trainingnavtop=true 6 previous.title=Building a Simpler User Interface 7 previous.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 35 SDK</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 45 shows an activity (a single screen) with a text field and a button. In this lesson, youll add some 46 code to <code>MainActivity</code> that 47 starts a new activity when the user clicks 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 54 href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a> 55 attribute 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 66 href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code 67 android:onClick}</a> attributes value, <code>"sendMessage"</code>, is the name of a method in your 68 activity that the system calls when the user clicks the button.</p> 69 70 <p>Open the <code>MainActivity</code> class and add the corresponding method:</p> 71 72 <pre> 73 /** Called when the user clicks the Send button */ 74 public 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>In order for the system to match this method to the method name given to <a 83 href="{@docRoot}reference/android/view/View.html#attr_android:onClick">{@code android:onClick}</a>, 84 the 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 90 android.view.View} that was clicked)</li> 91 </ul> 92 93 <p>Next, youll fill in this method to read the contents of the text field and deliver that text to 94 another 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 101 components (such as two activities). The {@link android.content.Intent} represents an 102 apps "intent to do something." You can use intents for a wide 103 variety of tasks, but most often theyre used to start another activity.</p> 104 105 <p>Inside the {@code sendMessage()} method, create an {@link android.content.Intent} to start 106 an activity called {@code DisplayMessageActivity}:</p> 107 108 <pre> 109 Intent 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 115 android.content.Context} as its first parameter ({@code this} is used because the {@link 116 android.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 118 the {@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} 126 specifies the exact app component to which the intent should be given. However, intents 127 can also be <em>implicit</em>, in which case the {@link android.content.Intent} does not specify 128 the desired component, but allows any app installed on the device to respond to the intent 129 as long as it satisfies the meta-data specifications for the action that's specified in various 130 {@link android.content.Intent} parameters. For more information, see the class about <a 131 href="{@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} 136 will raise an error if youre using an IDE such as Eclipse because the class doesnt exist yet. 137 Ignore the error for now; youll create the class soon.</p> 138 139 <p>An intent not only allows you to start another activity, but it can carry a bundle of data to the 140 activity as well. So, use {@link android.app.Activity#findViewById findViewById()} to get the 141 {@link android.widget.EditText} element and add its text value to the intent:</p> 142 143 <pre> 144 Intent intent = new Intent(this, DisplayMessageActivity.class); 145 EditText editText = (EditText) findViewById(R.id.edit_message); 146 String message = editText.getText().toString(); 147 intent.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 151 pairs called <em>extras</em>. The {@link android.content.Intent#putExtra putExtra()} method takes the 152 key name in the first parameter 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 key using a 155 public constant. So add the {@code EXTRA_MESSAGE} definition to the top of the {@code 156 MainActivity} class:</p> 157 158 <pre> 159 public class MainActivity extends Activity { 160 public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; 161 ... 162 } 163 </pre> 164 165 <p>It's generally a good practice to define keys for intent extras using your app's package name 166 as a prefix. This ensures they are 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 172 startActivity()} and pass it your {@link android.content.Intent}. The system receives this call 173 and starts an instance of the {@link android.app.Activity} 174 specified by the {@link android.content.Intent}.</p> 175 176 <p>With this new code, the complete {@code sendMessage()} method that's invoked by the Send 177 button now looks like this:</p> 178 179 <pre> 180 /** Called when the user clicks the Send button */ 181 public void sendMessage(View view) { 182 Intent intent = new Intent(this, DisplayMessageActivity.class); 183 EditText editText = (EditText) findViewById(R.id.edit_message); 184 String message = editText.getText().toString(); 185 intent.putExtra(EXTRA_MESSAGE, message); 186 startActivity(intent); 187 } 188 </pre> 189 190 <p>Now you need to create the {@code DisplayMessageActivity} class in order for this to 191 work.</p> 192 193 194 195 <h2 id="CreateActivity">Create the Second Activity</h2> 196 197 <div class="figure" style="width:400px"> 198 <img src="{@docRoot}images/training/firstapp/adt-new-activity.png" alt="" /> 199 <p class="img-caption"><strong>Figure 1.</strong> The new activity wizard in Eclipse.</p> 200 </div> 201 202 <p>To create a new activity using Eclipse:</p> 203 204 <ol> 205 <li>Click New <img src="{@docRoot}images/tools/eclipse-new.png" 206 style="vertical-align:baseline;margin:0" /> in the toolbar.</li> 207 <li>In the window that appears, open the <strong>Android</strong> folder 208 and select <strong>Android Activity</strong>. Click <strong>Next</strong>.</li> 209 <li>Select <strong>BlankActivity</strong> and click <strong>Next</strong>.</li> 210 <li>Fill in the activity details: 211 <ul> 212 <li><em>Project</em>: MyFirstApp</li> 213 <li><em>Activity Name</em>: DisplayMessageActivity</li> 214 <li><em>Layout Name</em>: activity_display_message</li> 215 <li><em>Navigation Type</em>: None</li> 216 <li><em>Hierarchial Parent</em>: com.example.myfirstapp.MainActivity</li> 217 <li><em>Title</em>: My Message</li> 218 </ul> 219 <p>Click <strong>Finish</strong>.</p> 220 </li> 221 </ol> 222 223 <p>If you're using a different IDE or the command line tools, create a new file named 224 {@code DisplayMessageActivity.java} in the project's <code>src/</code> directory, next to 225 the original {@code MainActivity.java} file.</p> 226 227 <p>Open the {@code DisplayMessageActivity.java} file. If you used Eclipse to create it, the class 228 already includes an implementation of the required {@link android.app.Activity#onCreate onCreate()} 229 method. There's also an implementation of the {@link android.app.Activity#onCreateOptionsMenu 230 onCreateOptionsMenu()} method, but 231 you won't need it for this app so you can remove it. The class should look like this:</p> 232 233 <pre> 234 public class DisplayMessageActivity extends Activity { 235 @Override 236 public void onCreate(Bundle savedInstanceState) { 237 super.onCreate(savedInstanceState); 238 setContentView(R.layout.activity_display_message); 239 } 240 } 241 </pre> 242 243 <p>All subclasses of {@link android.app.Activity} must implement the {@link 244 android.app.Activity#onCreate onCreate()} method. The system calls this when creating a new 245 instance of the activity. It is where you must define the activity layout and where you should 246 perform initial setup for the activity components.</p> 247 248 249 250 <h3 id="AddToManifest">Add it to the manifest</h3> 251 252 <p>You must declare all activities in your manifest file, <code>AndroidManifest.xml</code>, using an 253 <a 254 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element.</p> 255 256 <p>When you use the Eclipse tools to create the activity, it creates a default entry. It should 257 look like this:</p> 258 259 <pre> 260 <application ... > 261 ... 262 <activity 263 android:name=".DisplayMessageActivity" 264 android:label="@string/title_activity_display_message" > 265 <meta-data 266 android:name="android.support.PARENT_ACTIVITY" 267 android:value="com.example.myfirstapp.MainActivity" /> 268 </activity> 269 </application> 270 </pre> 271 272 <p>The <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code 273 <meta-data>}</a> element declares the name of this activity's parent activity 274 within the app's logical hierarchy. The Android <a 275 href="{@docRoot}tools/extras/support-library.html">Support Library</a> uses this information 276 to implement default navigation behaviors, such as <a 277 href="{@docRoot}design/patterns/navigation.html">Up navigation</a>.</p> 278 279 <p class="note"><strong>Note:</strong> During <a 280 href="{@docRoot}sdk/installing/adding-packages.html">installation</a>, you should have downloaded 281 the latest Support Library. Eclipse automatically includes this library in your app project (you 282 can see the library's JAR file listed under <em>Android Dependencies</em>). If you're not using 283 Eclipse, you may need to manually add the library to your project—follow this guide for <a 284 href="{@docRoot}tools/extras/support-library.html#SettingUp">setting up the Support Library</a>.</p> 285 286 <p>The app is now runnable because the {@link android.content.Intent} in the 287 first activity now resolves to the {@code DisplayMessageActivity} class. If you run the app now, 288 clicking the Send button starts the second activity, but it's still using the default 289 "Hello world" layout.</p> 290 291 292 <h2 id="ReceiveIntent">Receive the Intent</h2> 293 294 <p>Every {@link android.app.Activity} is invoked by an {@link android.content.Intent}, regardless of 295 how the user navigated there. You can get the {@link android.content.Intent} that started your 296 activity by calling {@link android.app.Activity#getIntent()} and retrieve the data contained 297 within it.</p> 298 299 <p>In the {@code DisplayMessageActivity} classs {@link android.app.Activity#onCreate onCreate()} 300 method, get the intent and extract the message delivered by {@code MainActivity}:</p> 301 302 <pre> 303 Intent intent = getIntent(); 304 String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 305 </pre> 306 307 308 309 <h2 id="DisplayMessage">Display the Message</h2> 310 311 <p>To show the message on the screen, create a {@link android.widget.TextView} widget and set the 312 text using {@link android.widget.TextView#setText setText()}. Then add the {@link 313 android.widget.TextView} as the root view of the activitys layout by passing it to {@link 314 android.app.Activity#setContentView setContentView()}.</p> 315 316 <p>The complete {@link android.app.Activity#onCreate onCreate()} method for {@code 317 DisplayMessageActivity} now looks like this:</p> 318 319 <pre> 320 @Override 321 public void onCreate(Bundle savedInstanceState) { 322 super.onCreate(savedInstanceState); 323 324 // Get the message from the intent 325 Intent intent = getIntent(); 326 String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 327 328 // Create the text view 329 TextView textView = new TextView(this); 330 textView.setTextSize(40); 331 textView.setText(message); 332 333 // Set the text view as the activity layout 334 setContentView(textView); 335 } 336 </pre> 337 338 <p>You can now run the app. When it opens, type a message in the text field, click Send, 339 and the message appears on the second activity.</p> 340 341 <img src="{@docRoot}images/training/firstapp/firstapp.png" /> 342 <p class="img-caption"><strong>Figure 2.</strong> Both activities in the final app, running 343 on Android 4.0. 344 345 <p>That's it, you've built your first Android app!</p> 346 347 <p>To learn more about building Android apps, continue to follow the 348 basic training classes. The next class is <a 349 href="{@docRoot}training/basics/activity-lifecycle/index.html">Managing the Activity 350 Lifecycle</a>.</p> 351 352 353 354 355