page.title=Starting Another Activity parent.title=Building Your First App parent.link=index.html trainingnavtop=true page.tags=intents helpoutsWidget=true @jd:body
After completing the previous lesson, you have an app that
shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some
code to MainActivity that
starts a new activity when the user clicks the Send button.
res/layout/activity_main.xml, add the
{@code android:onClick}
attribute to the {@link android.widget.Button <Button>} element as
shown below:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
This attribute tells the system to call the sendMessage()
method in your activity whenever a user clicks on the button.
java/com.example.myfirstapp/MainActivity.java,
add the sendMessage() method stub as shown below:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
}
In order for the system to match this method to the method name given to {@code android:onClick}, the signature must be exactly as shown. Specifically, the method must:
Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.
An {@link android.content.Intent} is an object that provides runtime binding between separate components (such as two activities). The {@link android.content.Intent} represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.
In MainActivity.java, add the code shown below to
sendMessage():
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Note: Android Studio will display
Cannot resolve symbol errors because the code references classes
like {@link android.content.Intent} and {@link android.widget.EditText}
that have not been imported. To import these classes, you can either 1)
use Android Studio's "import class" functionality by pressing Alt + Enter
(Option + Return on Mac) or 2) manually add import statements at the top of
the file.
There’s a lot going on in sendMessage(), so let’s explain
what's going on.
The {@link android.content.Intent} constructor takes two parameters:
Note: The reference to
DisplayMessageActivity will raise an error in Android Studio
because the class doesn’t exist yet. Ignore the error for now; you’ll
create the class soon.
The {@link android.content.Intent#putExtra(String, String) putExtra()}
method adds the EditText's value to the intent. An Intent
can carry data types as key-value pairs called extras. Your key is a
public constant EXTRA_MESSAGE because the next
activity uses the key to retrive the text value. It's a good practice to
define keys for intent extras using your app's package name as a prefix. This
ensures the keys are unique, in case your app interacts with other apps.
The {@link android.app.Activity#startActivity(Intent) startActivity()}
method starts an instance of the DisplayMessageActivity specified
by the {@link android.content.Intent}. Now you need to create the class.
Android Studio automatically does three things:
DisplayMessageActivity.java with an
implementation of the required {@link android.app.Activity#onCreate(Bundle) onCreate()}
method.activity_display_message.xml
AndroidManifest.xml.
If you run the app and click the Send button on the first activity, the second activity starts but is empty. This is because the second activity uses the default empty layout provided by the template.
Now you will modify the second activity to display the message that was passed by the first activity.
onCreate() method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
There’s a lot going on here, so let’s explain:
TextView to the layout identified by
{@code R.id.activity_display_message}. You cast the layout to
{@link android.view.ViewGroup} because it is the superclass of all layouts and
contains the {@link android.view.ViewGroup#addView(View) addView()}
method.Note: The XML layout generated by previous
versions of Android Studio might not include the android:id
attribute. The call findViewById() will fail if the layout
does not have the android:id attribute. If this is the case,
open activity_display_message.xml and add the attribute
android:id="@+id/activity_display_message" to the layout element.
You can now run the app. When it opens, type a message in the text field, and click Send. The second activity replaces the first one on the screen, showing the message you entered in the first activity.
That's it, you've built your first Android app!
To learn more, follow the link below to the next class.