Android Training/Starting Another Activity
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 MyActivity
that starts a new activity when the user clicks the Send button.
Respond to the Send ButtonEdit
- In Android Studio, from the
res/layout
directory, edit thecontent_my.xml
file. - Add the
android:onClick
attribute to the<Button>
element.- res/layout/content_my.xml
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" />
- The
android:onClick
attribute’s value,"sendMessage"
, is the name of a method in your activity that the system calls when the user clicks the button.
- res/layout/content_my.xml
- In the
java/com.mycompany.myfirstapp
directory, open theMyActivity.java
file. - Within the
MyActivity
class, add thesendMessage()
method stub shown below.- java/com.mycompany.myfirstapp/MyActivity.java
/** 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:
- Be public
- Have a void return value
- Have a
View
as the only parameter (this will be theView
that was clicked)
- java/com.mycompany.myfirstapp/MyActivity.java
Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.
Build an IntentEdit
- In
MyActivity.java
, inside thesendMessage()
method, create anIntent
to start an activity calledDisplayMessageActivity
with the following code:- java/com.mycompany.myfirstapp/MyActivity.java
public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); }
- Note: The reference to
DisplayMessageActivity
will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon. The constructor used here 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) Android Studio indicates that you must import theIntent
class.
- java/com.mycompany.myfirstapp/MyActivity.java
- At the top of the file, import the
Intent
class:- java/com.mycompany.myfirstapp/MyActivity.java
import android.content.Intent;
- Tip: In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
- java/com.mycompany.myfirstapp/MyActivity.java
- Inside the
sendMessage()
method, usefindViewById()
to get theEditText
element.- java/com.mycompany.myfirstapp/MyActivity.java
public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); }
- java/com.mycompany.myfirstapp/MyActivity.java
- At the top of the file, import the
EditText
class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. - Assign the text to a local
message
variable, and use theputExtra()
method to add its text value to the intent.- java/com.mycompany.myfirstapp/MyActivity.java
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); }
- An
Intent
can carry data types as key-value pairs called extras. TheputExtra()
method takes the key name in the first parameter and the value in the second parameter.
- java/com.mycompany.myfirstapp/MyActivity.java
- At the top of the
MyActivity
class, add theEXTRA_MESSAGE
definition as follows:- java/com.mycompany.myfirstapp/MyActivity.java
public class MyActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; ... }
- For the next activity to query the extra data, you should define the key for your intent's extra using a public constant. It's generally 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.
- java/com.mycompany.myfirstapp/MyActivity.java
- In the
sendMessage()
method, to finish the intent, call thestartActivity()
method, passing it theIntent
object created in step 1.
With this new code, the complete sendMessage()
method that's invoked by the Send button now looks like this:
java/com.mycompany.myfirstapp/MyActivity.java
/** 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);
}
The system receives this call and starts an instance of the Activity
specified by the Intent
. Now you need to create the DisplayMessageActivity
class in order for this to work.
Create the Second ActivityEdit
All subclasses of Activity
must implement the onCreate()
method. This method is where the activity receives the intent with the message, then renders the message. Also, the onCreate()
method must define the activity layout with the setContentView()
method. This is where the activity performs the initial setup of the activity components.
Create a new activity using Android StudioEdit
Android Studio includes a stub for the onCreate()
method when you create a new activity. The New Android Activity window appears.
- In Android Studio, in the
java
directory, select the package, com.mycompany.myfirstapp, right-click, and select New > Activity > Blank Activity. - In the Choose options window, fill in the activity details:
- Activity Name: DisplayMessageActivity
- Layout Name: activity_display_message
- Title: My Message
- Hierarchical Parent: com.mycompany.myfirstapp.MyActivity
- Package name: com.mycompany.myfirstapp Click Finish.
- Open the
DisplayMessageActivity.java
file. The class already includes an implementation of the requiredonCreate()
method. You update the implementation of this method later.
If you're developing with Android Studio, you can run the app now, but not much happens. Clicking the Send button starts the second activity, but it uses a default "Hello world" layout provided by the template. You'll soon update the activity to instead display a custom text view.
Create the activity without Android StudioEdit
If you're using a different IDE or the command line tools, do the following:
- Create a new file named
DisplayMessageActivity.java
in the project'ssrc/
directory, next to the originalMyActivity.java
file. - Add the following code to the file:
public class DisplayMessageActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle app bar item clicks here. The app bar // automatically handles clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_display_message, container, false); return rootView; } } }
- Note: If you are using an IDE other than Android Studio, your project does not contain the
activity_display_message
layout that's requested bysetContentView()
. That's OK because you will update this method later and won't be using that layout.
- To your
strings.xml
file, add the new activity's title as follows:<resources> ... <string name="title_activity_display_message">My Message</string> </resources>
- In your manifest file,
AndroidManifest.xml
, within theApplication
element, add the<activity>
element for yourDisplayMessageActivity
class, as follows:<application ... > ... <activity android:name="com.mycompany.myfirstapp.DisplayMessageActivity" android:label="@string/title_activity_display_message" android:parentActivityName="com.mycompany.myfirstapp.MyActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.mycompany.myfirstapp.MyActivity" /> </activity> </application>
The android:parentActivityName
attribute declares the name of this activity's parent activity within the app's logical hierarchy. The system uses this value to implement default navigation behaviors, such as Up navigationon Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for older versions of Android by using the Support Library and adding the <meta-data>
element as shown here.
Note: Your Android SDK should already include the latest Android Support Library, which you installed during the Adding SDK Packages step. When using the templates in Android Studio, the Support Library is automatically added to your app project (you can see the library's JAR file listed under Android Dependencies). If you're not using Android Studio, you need to manually add the library to your project—follow the guide for setting up the Support Library then return here.
If you're using a different IDE than Android Studio, don't worry that the app won't yet compile. You'll soon update the activity to display a custom text view.
Receive the IntentEdit
Every Activity
is invoked by an Intent
, regardless of how the user navigated there. You can get the Intent
that started your activity by calling getIntent()
and retrieve the data contained within the intent.
- In the
java/com.mycompany.myfirstapp
directory, edit theDisplayMessageActivity.java
file. - Get the intent and assign it to a local variable.
Intent intent = getIntent();
- At the top of the file, import the
Intent
class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes. - Extract the message delivered by
MyActivity
with thegetStringExtra()
method.String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
Display the MessageEdit
- In the res/layout directory, edit the
content_display_message.xml
file. - Add an
android:id
attribute to theRelativeLayout
. You need this attribute to reference the object from your app code.< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ... android:id="@+id/content"> </RelativeLayout>
- Switch back to editing
DisplayMessageActivity.java
. - In the
onCreate()
method, create aTextView
object.TextView textView = new TextView(this);
- Set the text size and message with
setText()
.textView.setTextSize(40); textView.setText(message);
- Add the
TextView
to theRelativeLayout
identified byR.id.content
.RelativeLayout layout = (RelativeLayout) findViewById(R.id.content); layout.addView(textView);
- At the top of the file, import the
TextView
class. In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
The complete onCreate()
method for DisplayMessageActivity
now looks like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
layout.addView(textView);
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!
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.