Sunday, May 9, 2010

How do I – Android: create a new activity?

Only a very simple applications consist of one form (activity). To create new activity in Android (Eclipse) follow these steps:

1. Open your project in Eclipse
2. Expand your project folder structure down to the “layout” folder and call a context menu on this folder:

image

3. Select “New” –> “Android XML File” from context menu:

image

4. Once you click this menu item a new Android XML file dialog will be opened where you will need to fill at least “File” field, all other fields are optional.

image

Press “Finish” and you will get a new activity in your Android project.

Well, now when you have your layout defined, you need to create a class representing this activity (it is not necessary in some cases)..

To create a new class that will be used to show your activity just defined on screen you need to:

1. Select “File” –> “New” –> “Class…”
2. Specify source folder and package name – by default that will be “src” folder under your project tree;
3. Provide name for you class – its better to give your class name same as you gave your layout file (for instance, if your layout name is “aboutform.xml”, than name your class “aboutform.java”);
4. Specify superclass – the one that you want to inherit from – it must be android.app.Activity);

image

5. Press “Finish…”

Now, when you have your class and layout – you need to “connect” layout and class. You can do that by specifying which layout your activity must use in onCreate method of your activity.

1. Override onCreate method, put the following code in your activity class:

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

 

public class Second extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // ...
      }
}

Read more about activity lifetime here!

A sidenote: when you create a new layout an Eclipse automatically regenerates a resources and puts a new resource identifier in R class (can be found in “gen” folder under your project tree). For instance, you’ve added a new layout with name “second".xml”, it means that when R file will gets regenerated you will see a new resource R.layout.second and it will be available from your code (as your layout identifier).

2. To specify which layout must be displayed use setContentView method and specify target layout Id:

this.setContentView(R.layout.second);

Final version should look like the following:

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

public class Second extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.second); 
      }
}

That’s all, you can use your activity.

2 comments :