Android Tutorial (6) – How to create and display a new form, window or activity

11 comments - This post in romanian

In this post we will see what are the basics for developing an Android mobile application that has multiple windows or activities. To do that, we need to know how to create and display a new form, window or activity (for the rest of the post we will use the Android vocabulary and call it just activity).

We have seen in the previous parts of the Android Tutorial which are the fundamentals of an Android application and its components. Also we have seen that behind a window there is an Activity type instance that has a lifecycle and a display.


Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents.
The sketch of the Android mobile application described in this post (the Eclipse project for the example is available at the end of the post) is:

Android Example Sketch

Android Example Sketch

To achieve the proposed objective, to create and display a new Activity, we define the solution steps:

  1. define a widget on the main activity display used to open the new Activity;
  2. define the new Activity and its layout; also declare the activity in the Android application manifest file, the AndroidManifest.xml;
  3. define in the main activity the event and its handler that will display the new Activity;

We will start by creating the skeleton Android project using the Eclipse ADT plugin with the next settings:

  • Project Name: AndroidSecondActivity
  • Build target: Android 2.3.3
  • Application Name: Create and display a new Activity
  • Package name: eu.itcsolutions.android.tutorial
  • Create Activity: MainActivity
  • Min SDK Version: 10

Step 1. The main Activity user interface will be designed in a declarative manner because we will use Java code for more complex things. In order to open the new Activity we will provide a Button on the display. When the user clicks it, the new Activity will be displayed.

1.1. Edit the project /res/values/strings.xml file and add a new item. Use the text editor and not the Resources visual editor, as the first one is faster. Add the item after the existing ones, on line 5 (hello is for the TextView and app_name is for the main Activity title bar):

 1: <?xml version="1.0" encoding="utf-8"?>
 2: <resources>
 3:     <string name="hello">Hello World, MainActivity!</string>
 4:     <string name="app_name">Create and display a new Activity</string>
 5:     <string name="btnClick">Click me !</string>
 6: </resources>

 

1.2. Add a Button instance on the display by editing the project /res/layout/main.xml. You can delete the existing TextView that has the hello message. The Button instance properties that we initialize are:

  • Text: the btnClick string in strings.xml file. If you use the declarative design then the element is accessed using “@string/btnClick”. For procedural design the string resource is accessed using getString(R.string.btnClick).
  • Width: wrap_content which is equal to the size of the text;
  • Height: wrap_content
  • Id: buttonClick. If you use the declarative design then the id of the Button instance is defined using the android:id property. The property gets a value with the “@+id/id_name” syntax. The android:id property is the equivalent of the Button reference when writing Java code and it will be used to refer that particular Button instance (remember that when you use declarative design you don’t write any Java code, but later you may want to access the Button from the code). If you use the graphical layout editor to place the button on the screen, it will generate a default id (android:id=”@+id/button1″) for the Button instance. If you don’t use the graphical layout editor add it in the <Button> description.

Either you use the layout graphical layout editor or not, the main.xml file should look like this (I have deleted the existing TextView and centered the content using of the android:gravity attribute of the LinearLayout element:

<?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"
    android:gravity="center_vertical|center_horizontal"
    >
<Button
    android:text="@string/btnClick"
    android:id="@+id/buttonClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
</LinearLayout>

Step 2.To define a new Activity we must create a new class that extends Activity and also a new layout for it. To do that we have two possibilities. One is to get our hands dirty and write everything form zero and the second option is to use the Manifest visual editor (a WYSIWYG editor with tabs at the bottom which is opened by default when you select the manifest file) that generates part of the needed code (see How to create a new Activity class with the Manifest editor or without it). In this example I will use the first approach. To open the simple XML text editor, select the tab with the manifest file name on it (the last tab) from the WYSIWYG editor.

2.1. The class is created as a common Java class, using File –> New –> Class. Name it SecondActivity and set android.app.Activity as its superclass:

New Activity dialog

New Activity dialog

2.2. Because the ADT plugin is not so helpful when creating a new Activity class, in this manner, you must edit it from scratch:

package eu.itcsolutions.android.tutorial;
 
import android.app.Activity;
import android.os.Bundle;
 
public class SecondActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
    }
}

2.3. Let’s define a layout for the new Activity. For that, Eclipse is somehow helpful because there is a New Android XML File wizard. To open it, select the project and use File –> New –> Other and from the Android category select Android XML File.

New Android XML File dialog

New Android XML File dialog

Name the new layout file, second.xml and edit it by placing a TextView on it. The text of the TextView is set in the layout file (not recommended).

<?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:layout_width="match_parent"
  android:layout_height="match_parent"
  android:text="This is the second Activity"
/>
</LinearLayout>

2.4. Link the layout file second.xml with the SecondActivity by calling setContentView() in the class onCreate() method:

        this.setContentView(R.layout.second);

2.5. Important ! Declare the SecondActivity in the Android project manifest file, AndroidManifest.xml. To do that, you can use the Android Manifest Application tab or you can use the XML text editor (the AndroidManifest.xml tab). I will use the latter option and I will add the next line in the XML file, between <application> and </application> (after the main Activity declaration):

<activity
        android:name="SecondActivity"
        android:label="Second Activity">
</activity>

 

Step 3. The event that will display the second activity is generated when the user clicks the button. The event-handler architecture is the same as in any Java JSE application. The event is managed by the system and the application defines and register listeners for that event.

3.1. The event listener is the button from the main Activity. To register it as a listener we must reference the button instance from Java code. But the button has been defined in the XML layout file.

Important !
To get the reference of a View item, defined in the layout XML file, you can use the View class findViewById(int ID) method. As argument, use the static constant from the R generated class. Also, the XML element must have an android:id attribute with a “@+id/id_name like value.

After we get the Button reference with a call to findViewById(int ID) method, we register it as a listener using setOnCLickListener() method. This is done in the main Activity onCreate() method after the call to setContentView():

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.main);
 
	//get the Button reference
	//Button is a subclass of View
	//buttonClick is defined in main.xml "@+id/buttonClick"
        View v = findViewById(R.id.buttonClick);
	//set event listener
        v.setOnClickListener(this);
    }

After adding the previous code, you will get a compiler error. We will solve it right away.

As you can see, the setOnCLickListener(OnCLickListener l) method requires a reference to an instance of a class that implements the OnClickListener interface, providing a handler for the event.

3.2. The define a handler for the OnClick event we will implement the android.view.View.OnClickListener interface. The interface has an abstract method, onClick(), that we must override. Modify the MainActivity class:

//implement the OnClickListener interface
public class MainActivity extends Activity
	implements OnClickListener {
 
    	...
 
    	//overrides the OnClickListener interface method
	@Override
	public void onClick(View arg0) {
 
	}
}

3.3. The onClick(View arg0) method parameter represents the reference to the widget that launched the event when it was clicked. We compare it to our button reference (we have a single button, but it is best practice to check it).

3.4. As you remember from Android Tutorial (02) – Applications key concepts, activities and resources, the Intent component represents an asynchronous message used to activate activities. So if we want to display a new activity we must do use an Intent reference. The second activity is displayed using the startActivity() method of the Activity class.

@Override
public void onClick(View arg0) {
	if(arg0.getId() == R.id.buttonClick){
		//define a new Intent for the second Activity
		Intent intent = new Intent(this,SecondActivity.class);
 
		//start the second Activity
		this.startActivity(intent);
	}
}

 

Run and test the Android application. To return to the main activity, use the return button of the emulator keypad.

Important !
DO NOT FORGET to declare the SecondActivity in the manifest file. Without that you will get a ActivityNotFoundException and an explicit error message.

 

It it helps you can check the Android project source.

If you have problems with the examples or you don’t understand our explanations, put a question in the comments and we will help you. Also, any suggestion or comment that will improve this material is appreciated.

Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents.

Like it? Then share this post or check the external adds. Sharing is the best way to appreciate the author.

,


  1. #1 by Alex on September 7th, 2011

    Android project source link is invalid :-(

    • #2 by Catalin on September 10th, 2011

      HI Alex,

      Thank you for the observation. Now, the link is up and the problem has been solved.

  2. #4 by Ces on September 26th, 2011

    nice example, just have a question, what if i want to add a button to return to the previous page?

    thanks a lot.

    • #5 by Catalin on September 26th, 2011

      Hi Ces,

      By default the return key of the device will bring back to foreground the previous Activity.

      If you want an explicit Back button (on the screen or in the menu) you can use the same principles as in this article. The difference is that when selecting the Back button you must use the Intent to close the current Activity and to return a response to the calling Activity.
      Because running Activities are manage by a stack, closing the current one will bring back the previous one.

      A possible solution for the Back button onClick handler is:

      //create a new Intent
      Intent intent = new Intent();
      //set the result for the caller
      setResult(RESULT_OK, intent);
      //close current Activity
      finish();

      The returning result is useful if you have started the new Activity with startActivityForResult(Intent intent, int requestCode) instead of startActivity(Intent intent) and also if you override the onActivityResult(int, int, Intent) method in the calling Activity.

      If you have problems with this, I will put a new article on it.

  3. #6 by Naveenraj xavier on February 14th, 2012

    Very Very Very thanks …….Very helpful for Beginners

  4. #7 by hardik on March 31st, 2012

    Hey..while linking the second.xml file with the second activity class it is showing an error on ‘second’-”second can not be resolved or is not a field??” buggin’ me a lot!!

  5. #8 by Ravi Joshi on April 14th, 2012

    Hi,
    I am a beginner in Android app development and was trying to write an app with more than one widget. This post of yours exactly showed me how to do it. I guess developing any application with multiple widgets is so simple now.

    Can you kindly provide some pointers/examples of how to develop applications like Angry bird (for e.g) which is more complex and involve lot of graphical content.

    Thanks & Regards,
    -Ravi

  6. #9 by harsh on March 9th, 2013

    thanks…..
    it worked

(will not be published)