Thursday, 1 December 2011

Android - Creating a new Activity in Eclipse

The method of creating new Activities in Eclipse is somewhat counter-intuitive if you ask me.

Open your manifest file, which is likely called "AndroidManifest.xml" if you've stuck with defaults. You should see multiple tabs at the bottom, which will give you different views on the one manifest file. Choose the "Application" tab.

You'll see a horribly cluttered screen here, with one of the sections named as "Application Nodes"; this lists all of your existing Activities and allows you to add new ones. Nodes...? C'mon Google!! Anyway, hit the "Add..." button.

You'll see the following prompt:

Choose "Activity" from this list. This will create a new section named as "Attributes for Activity" to the right of "Application Nodes". Don't be tempted to go filling in values yet. See the hyperlinked text, "Name*", yup, click on that:

This will launch the "New Class Wizard" with the superclass already set appropriately for you. Name your class, choose your package as you normally would.

The last step is to add a new layout XML for the Activity (assuming you need one). Under your project, there will be a folder named "res", and under that a folder named "layout". Right click on "layout", and choose "New", then "Other...". Select "Android XML Layout File" from the list.

Give it a name that corresponds to your Activity in some meaningful way, but you are limited as to what characters you can use:
 File-based resource names must contain only lowercase a-z, 0-9, or _
Once created, open your new Activity class up, and you'll see the onCreate method has been templated for you. After the line, super.onCreate(savedInstanceState); add the following:
If Eclipse fails to autocomplete once you have typed R, it could be because it has imported android.R automatically and not your own R class. Simply the delete the following line if it exists:
import android.R;
After that, organize your imports  (CTRL+SHIFT+O) and if prompted, choose your own R class and not the default android.R.