Start New Activity



In an Android application, every individual UI entity is an activity. An activity comprised of a Java code file and an XML layout (UI) file. If you are a web developer, then you may think activity equivalent to a web page.

Add new activity:

Add New Activity Menu

To add new Activity in an application, just right click on the project name, New -> Activity -> choose the type of Activity you want to add in the project. Most of the time, we choose an Empty Activity.

Add New Activity  Wizard

Give Activity a name, depending on the name you are giving Android Studio name the XML layout file, though you may change the layout name it is advised to let it remain default. If you want to update the launcher activity to the newly created activity, then check the Launcher Activity checkbox. For now, we are keeping everything to default and click Finish button.

Android Studio has created the Java file and XML file in respective locations for the Activity. Add following code in the activity_second.xml file just to differentiate the new activity.

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Activity"
android:textSize="30dp" />

Start the New Activity:

After adding new Activity in our application, let us learn how can we start the activity. In our example, we want to start the new activity on a button click on MainActivity. Let's add a button in the MainActivity. Add following code in the XML Layout file i.e. activity_main.xml

<Button
android:layout_width="368dp"
android:layout_height="wrap_content"
android:text="New Activity"
android:onClick="newActivity"
/>

In the Java file (MainActivity) create a new method with name "newActivity". When the user of application tap on this button, this method will be invoked. Code for the methods is as follows:

public void newActivity(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}

In this, we are creating a new Intent object in which first we pass the context of current Activity and the second argument is the class file of new Activity which we need to start. After creating the object, we pass it to the startActivity method.

Let us run the app and see it in action.

Start New Activity Demo

In this article, we touched a few topics which are:
  • Add a new Activity (using a graphical wizard of Android Studio)
  • Button click Event (Using onClick property in XML file)
  • Start a new Activity (Using Java Code by creating an Intent object)

In the next article, we will see how to pass data values from one activity to another activity. Before moving to that topic, it is advised that you practice and master these concepts discussed above, these are the base for the next topic.