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