Creating Another Activity – Intro to Android Intents

So we’ve learned how to create a simple window using Android Studio IDE and the Android SDK, now let’s make another. Not just recreate the same project, but introduce Android¬†Intents which can be used to call new Activities.

The Android Developer website describes Intents as messaging objects that can be used to request an action from another app component. Since an activity is an app component, let’s test that theory.

Start Creating Intents

Start by creating a new project with an Empty Activity template. If you haven’t created a project before, check out my “Creating Your First Android Project” post. I will be using ActivityIntent as the application name and ParentActivity as the main activity name.

Create a new Activity from the menu bar by clicking File > New… > Activity > Empty Activity

I’ve named the new activity ChildActivity as you’ll see in the next code snippet.

Add the following under the onCreate method’s closing curly brace (‘}‘):

public void onClickChildActivity(View view){
    Intent intent = new Intent(this, ChildActivity.class);
    startActivity(intent);
}

Android-Intro-Intents-Parent-Activity

Open up your activity_parent.xml file in the res/layout directory and add the following button:

<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:text="Launch Child" android:onClick="onClickChildActivity" />

Android-Intro-Intents-Parent-Layout

Notice the onClick event that we’ve declared in the button. This matches the method we had created earlier in the ParentActivity class which declares and invokes our intent.

You might be wondering how the button knows to look in the ParentActivity.java file. If you have a look at your ParentActivity.java file you’ll see a setContentView method called within the onCreate method. This method takes a single parameter which is the layout resource with what the activity will contain.

At this point, the application is ready to be deployed. You’ll see a screen similar to the last project, but this time it will have a button. Press this button and another activity will appear!

This is our button firing an onClick event which points to our onClickChildActivity method, which then creates our intent used to launch a new activity.

Time to Discover

Play around with it a bit, watch what happens when you change the setContentView parameter to activity_child instead of activity_parent. Try changing the parameter to something that isn’t instantiated, what happens then?

 

Leave a Reply

Your email address will not be published. Required fields are marked *