In the this lesson we will:

- create and invoke second Activity in our application

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

 

We have reached a very interesting topic. In all the previous lessons we have been creating applications, which included only one screen (Activity). But if you use Android smartphone, you have probably noticed, that there are usually more screens in the application. If to explore, for example, mail application - it has the following screens: list of accounts, list of messages, the message itself, settings, etc. It is high time for us to create multiple screen applications.

Let’s create a project:

 

Project name: P0211_TwoActivity
Build Target: Android 2.3.3
Application name: TwoActivity
Package name: ru.startandroid.develop.p0211twoactivity
Create Activity: MainActivity

 

Open main.xml and create this screen

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to Activity Two"
        android:id="@+id/btnActTwo">
    </Button>
</LinearLayout>

There is one button, clicking which will launch the second screen. 

 

Open MainActivity.java and write the following code:

package ru.startandroid.develop.p0211twoactivity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

  Button btnActTwo;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnActTwo = (Button) findViewById(R.id.btnActTwo);
    btnActTwo.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnActTwo:
      // TODO Call second activity
      break;
    default:
      break;
    }
  }
}

We have defined button btnActTwo and assigned it Activity as a listener. onClick method implementation is filled only partially for now - we define which button has been clicked. A little bit later we will invoke second screen here. But first we have to create this screen.

If you remember, when creating the project, Activity is created by default.

We only need to specify the name of this Activity - we usually write MainActivity here. Let’s look through what’s going on pening here. We already know that the class with the same name - MainActivity.java is created - it is responsible for Activity behavior. But Activity is also “registered” in the system using manifest-file - AndroidManifest.xml.

Let’s open this file:

We are interested in the Application tab. We can see MainActivity on the left. If you expand it, we can see an Intent Filter with specific parameters. We don’t know what is it for now and what is it used for. Running a little ahead, I can tell that android.intent.action.MAIN informs the system that the Activity is main and will be displayed the first when the application is launched. And android.intent.category.LAUNCHER means that the application will be listed in the device Android application list.

To the right in the Name field .MainActivity is written. It is the name of the class which is responsible for Activity’s job (it can also be considered as Activity name).

So if we want to create one more Activity, we have to create a class and register Activity in AndroidManifest.xml. To create a class, right click on the ru.startandroid.develop.p0211twoactivity package inside the project folder and choose New -> Class.

 

In the class window that just appeared - enter the name of the class - ActivityTwo and its superclass - android.app.Activity

 

ActivityTwo class is now created. It is empty for now. We have to implement onCreate method, which is invoked when Activity is created:

package ru.startandroid.develop.p0211twoactivity;

import android.app.Activity;
import android.os.Bundle;


public class ActivityTwo extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }
}

 

We also lack setContentView method invocation, which specifies how to fill the screen. This method requires layout-file as a parameter. Lets create it in the layout folder, the same folder where main.xml is located. We will name this file two.xml

 

Fill this file with the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is Activity Two">
    </TextView>
</LinearLayout>

The screen will display a TextView with “This is Activity Two” text.

Let’s use two.xml file in the setContentView method inside ActivityTwo.java

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.two);
  }

(add only the highlighted code)

Save everything. ActivityTwo class is ready, when it is created it will show on the screen what we have configured in two.xml layout-file. Now we need to register Activity in the manifest. Open AndroidManifest.xml, Application tab. Click the Add button

Then, in the window that just appeared, choose the item “Create a new element at the top level...” (if there is a choice), and choose Activity from the list

Press OK, Activity is now created and appeared in the list. The only thing is left is to point the class that will be responsible for its work. On the right, in the Name field we can manually write the name of the class which we have created = “ActivityTwo”. Or we can click Browse and choose the same Activity from the list (we will have to wait a short time while the list is being formed). We don’t need to fill in anything else for now. Save everything.

Now two Activities are registered in the manifest, and each of them points to its own class.

 

The only thing is left is to go back to MainActivity.java and finish onClick (button click) method implementation - invoke ActivityTwo. Open MainActivity.java and add the following lines:

    case R.id.btnActTwo:
      Intent intent = new Intent(this, ActivityTwo.class);
      startActivity(intent);
      break;

(add only the highlighted code)

 

Update imports (CTRL + SHIFT + O), save everything and you can now run it. When you launch the application, MainActivity appears.

Press the button and go to ActivityTwo

 

For now, I will not explain Activity invocation code and will not give any theory, the lesson is already quite complicated. There is lots of text and screenshots, but in reality the procedure is very short. It may be quite complicated for now, but eventually we will master it. We will create 5-6 new Activities in different projects and you will be good at this.

For now, try to repeat all this sequence in your mind and understand that for Activity creation we need to create a class (that extends android.app.Activity) and register it in the manifest-file.

 

In the next lesson we will:

- look through the code of lesson 21
- theory about Intent and Intent Filter (do not omit, the topic is very important)
- a little bit about Context


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language