This lesson teaches you to
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.
Respond to the Send Button
- In the file
res/layout/activity_main.xml
, add theandroid:onClick
attribute to the<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. - In the file
java/com.example.myfirstapp/MainActivity.java
, add thesendMessage()
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
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.
Build an Intent
An Intent
is an object that provides runtime binding
between separate components (such as two activities). The
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 Intent
and 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 Intent
constructor takes two parameters:
- A
Context
as its first parameter (this
is used because theActivity
class is a subclass ofContext
) - The
Class
of the app component to which the system should deliver theIntent
(in this case, the activity that should be started).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 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 startActivity()
method starts an instance of the DisplayMessageActivity
specified
by the Intent
. Now you need to create the class.
Create the Second Activity
- In the Project window, right-click the app folder and select New > Activity > Empty Activity.
- In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish
Android Studio automatically does three things:
- Creates the class
DisplayMessageActivity.java
with an implementation of the requiredonCreate()
method. - Creates the corresponding layout file
activity_display_message.xml
- Adds the required
<activity>
element in
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.
Display the Message
Now you will modify the second activity to display the message that was passed by the first activity.
- In
DisplayMessageActivity.java
, add the following code to theonCreate()
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); }
- Press Alt + Enter (option + return on Mac) to import missing classes.
There’s a lot going on here, so let’s explain:
- The call
getIntent()
grabs the intent that started the activity. EveryActivity
is invoked by anIntent
, regardless of how the user navigated there. The callgetStringExtra()
retrieves the data from the first activity. - You programmatically create a
TextView
and set its size and message. - You add the
TextView
to the layout identified byR.id.activity_display_message
. You cast the layout toViewGroup
because it is the superclass of all layouts and contains theaddView()
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.