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="#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
     33 shows an activity (a single screen) with a text field and a button. In this lesson, youll add some
     34 code to <code>MainActivity</code> that
     35 starts 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 <b>res > layout > activity_main.xml</b>, 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 <b>java > com.example.myfirstapp > MainActivity.java</b>,
     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, youll fill in this method to read the contents of the text field and deliver that text to
     86 another activity.</p>
     87 
     88 
     89 <h2 id="BuildIntent">Build an Intent</h2>
     90 
     91 <p>An {@link android.content.Intent} is an object that provides runtime binding
     92   between separate components (such as two activities). The
     93   {@link android.content.Intent} represents an apps "intent to do something."
     94   You can use intents for a wide variety of tasks, but in this lesson, your intent
     95   starts another activity.</p>
     96 
     97 <p>In <code>MainActivity.java</code>, add the code shown below to
     98   <code>sendMessage()</code>:</p>
     99 
    100 <pre>public class MainActivity extends AppCompatActivity {
    101     <b>public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";</b>
    102     &#64;Override
    103     protected void onCreate(Bundle savedInstanceState) {
    104         super.onCreate(savedInstanceState);
    105         setContentView(R.layout.activity_main);
    106     }
    107 
    108     /** Called when the user clicks the Send button */
    109     public void sendMessage(View view) {
    110         <b>Intent intent = new Intent(this, DisplayMessageActivity.class);
    111         EditText editText = (EditText) findViewById(R.id.edit_message);
    112         String message = editText.getText().toString();
    113         intent.putExtra(EXTRA_MESSAGE, message);
    114         startActivity(intent);</b>
    115     }
    116 }</pre>
    117 
    118 <p>Android Studio will display <b>Cannot
    119 resolve symbol</b> errors because this code references classes that are not
    120 imported. You can solve some of these with Android Studio's "import class"
    121 functionality by pressing Alt + Enter (or Option + Return on Mac).
    122 Your imports should end up as the following:</p>
    123 <pre>
    124 import android.content.Intent;
    125 import android.support.v7.app.AppCompatActivity;
    126 import android.os.Bundle;
    127 import android.view.View;
    128 import android.widget.EditText;
    129 </pre>
    130 
    131 <p>An error remains for <code>DisplayMessageActivity</code>, but that's okay;
    132 you'll fix that in the next section.
    133 
    134 
    135 <p>Theres a lot going on in <code>sendMessage()</code>, so lets explain
    136   what's going on.</p>
    137 
    138 <p>The {@link android.content.Intent} constructor takes two parameters:</p>
    139 <ul>
    140   <li>A {@link android.content.Context} as its first parameter ({@code this}
    141     is used because the {@link android.app.Activity} class is a subclass of
    142     {@link android.content.Context})
    143   <li>The {@link java.lang.Class} of the app component to which the system
    144     should deliver the {@link android.content.Intent} (in this case, the
    145     activity that should be started).
    146     <p class="note"><strong>Note:</strong> The reference to
    147       <code>DisplayMessageActivity</code> will raise an error in Android Studio
    148       because the class doesnt exist yet. Ignore the error for now; youll
    149       create the class soon.</p>
    150 </ul>
    151 
    152 <p>The {@link android.content.Intent#putExtra(String, String) putExtra()}
    153   method adds the <code>EditText</code>'s value to the intent. An <code>Intent</code>
    154   can carry data types as key-value pairs called <em>extras</em>. Your key is a
    155   public constant <code>EXTRA_MESSAGE</code> because the next
    156   activity uses the key to retrive the text value. It's a good practice to
    157   define keys for intent extras using your app's package name as a prefix. This
    158   ensures the keys are unique, in case your app interacts with other apps.</p>
    159 
    160 <p>The {@link android.app.Activity#startActivity(Intent) startActivity()}
    161   method starts an instance of the <code>DisplayMessageActivity</code> specified
    162   by the {@link android.content.Intent}. Now you need to create the class.</p>
    163 
    164 
    165 <h2 id="CreateActivity">Create the Second Activity</h2>
    166 
    167 <ol>
    168   <li>In the <b>Project</b> window, right-click the <b>app</b> folder and select
    169     <strong>New > Activity > Empty Activity</strong>.</li>
    170   <li>In the <strong>Configure Activity</strong> window, enter
    171     "DisplayMessageActivity" for <strong>Activity Name</strong> and click
    172     <strong>Finish</strong>
    173   </li>
    174 </ol>
    175 
    176 <p>Android Studio automatically does three things:</p>
    177 <ul>
    178   <li>Creates the class <code>DisplayMessageActivity.java</code> with an
    179    implementation of the required {@link android.app.Activity#onCreate(Bundle) onCreate()}
    180     method.</li>
    181   <li>Creates the corresponding layout file <code>activity_display_message.xml</code>
    182     </li>
    183   <li>Adds the required
    184     <a href="{@docRoot}guide/topics/manifest/activity-element.html"
    185     ><code>&lt;activity&gt;</code></a>
    186     element in <code>AndroidManifest.xml</code>.
    187 </ul>
    188 
    189 <p>If you run the app and click the Send button on the first activity, the
    190   second activity starts but is empty. This is because the second activity uses
    191   the default empty layout provided by the template.</p>
    192 
    193 <h2 id="DisplayMessage">Display the Message</h2>
    194 <p>Now you will modify the second activity to display the message that was passed
    195 by the first activity.</p>
    196 
    197 <ol>
    198   <li>In {@code DisplayMessageActivity.java}, add the following code to the
    199     <code>onCreate()</code> method:
    200     <pre>&#64;Override
    201 protected void onCreate(Bundle savedInstanceState) {
    202    super.onCreate(savedInstanceState);
    203    setContentView(R.layout.activity_display_message);
    204 
    205    Intent intent = getIntent();
    206    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    207    TextView textView = new TextView(this);
    208    textView.setTextSize(40);
    209    textView.setText(message);
    210 
    211    ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
    212    layout.addView(textView);
    213 }</pre>
    214   </li>
    215   <li>Press Alt + Enter (or Option + Return on Mac) to import missing classes.
    216   Your imports should end up as the following:
    217 <pre>
    218 import android.content.Intent;
    219 import android.support.v7.app.AppCompatActivity;
    220 import android.os.Bundle;
    221 import android.view.ViewGroup;
    222 import android.widget.TextView;
    223 </pre>
    224 </li>
    225 </ol>
    226 
    227 <p>Theres a lot going on here, so lets explain:</p>
    228 
    229 <ol>
    230   <li>The call {@link android.app.Activity#getIntent()} grabs the intent
    231     that started the activity. Every {@link android.app.Activity} is invoked by an
    232     {@link android.content.Intent}, regardless of how the user navigated there.
    233     The call {@link android.content.Intent#getStringExtra(String) getStringExtra()}
    234     retrieves the data from the first activity.</li>
    235   <li>You programmatically create a {@link android.widget.TextView} and set
    236     its size and message.
    237   </li>
    238   <li>You add the <code>TextView</code> to the layout identified by
    239     {@code R.id.activity_display_message}. You cast the layout to
    240     {@link android.view.ViewGroup} because it is the superclass of all layouts and
    241     contains the {@link android.view.ViewGroup#addView(View) addView()}
    242     method.</li>
    243 </ol>
    244 
    245 <p class="note"><strong>Note: </strong>The XML layout generated by previous
    246   versions of Android Studio might not include the <code>android:id</code>
    247   attribute. The call <code>findViewById()</code> will fail if the layout
    248   does not have the <code>android:id</code> attribute. If this is the case,
    249   open <code>activity_display_message.xml</code> and add the attribute
    250   <code>android:id="@+id/activity_display_message"</code> to the layout element.
    251 </p>
    252 
    253 <p>You can now run the app. When it opens, type a message in the text field, and click
    254 <strong>Send</strong>. The second activity replaces the first one on the screen, showing
    255 the message you entered in the first activity.</p>
    256 
    257 <p>That's it, you've built your first Android app!</p>
    258 
    259 <p>To learn more, follow the link below to the next class.</p>