Wednesday, 16 February 2011

Android: Adding a new Activity using Eclipse

To add a new screen to your android app you'll want to add a new activity. This is a slightly manual process however, so I've noted down here for future reference.

This example will add a new activity called 'Foo'.

Step 1 - Add the activity class
  • In the Package Explorer, right click your main package (e.g. com.calvium.myApp) and select New / Class
  • Set the new class Name (e.g. Foo.java), and set it the superclass to android.app.Activity
  • Add an override for the onCreate method.
  • Easy method: Open the new file and place your cursor inside the main { } block. Press CTRL-SPACE and up pops a list of possibilities. Type 'onCreate' and hit enter to generate the method stub.
  • After super.onCreate add:

setContentView(R.layout.foo);

Step 2 - Create the Activity Layout File
  • Back in the package explorer, right-click res / layout.
  • Select New / Other / Android / Android XML File
  • Call the new file foo.xml
  • Add whatever controls you want to the xml file using the designer tool in eclipse, or by typing stuff manually.
Step 3 - Register the new activity in the AndroidManifest.xml file
  • Open AndroidManifest.xml
  • Just before the closing tag insert:

<activity android:name=".Foo">activity>

5 comments:

  1. Thanks, this post helps me a lot :-)

    ReplyDelete
  2. Actually, there is a slightly easier way. Have a look at the following: http://www.itcsolutions.eu/2011/08/31/android-tutorial-how-to-create-a-new-activity-class-with-manifest-editor/

    ReplyDelete
    Replies
    1. Thanks Pandelon - I didn't know about that method.

      Delete
  3. thanks..This is what I was looking for, I found a one more example here http://androidtechstuffs.blogspot.in/2013/01/invoke-activity-from-another-activity.html. Have a look!!

    ReplyDelete