Recipe: Creating a Project and an Activity

A straightforward way to create an Android project or any of its components is to use the Eclipse Integrated Development Environment (IDE).This method ensures proper setup of the supporting files.The steps to create a new Android project are
  1. In Eclipse, choose File → New → Android Project.This displays a New Android Project creation screen.
  2. Fill in the Project name, such as SimpleActivityExample.
  3. Select a Build Target from the choices provided.These choices are based on the Software Development Kit (SDK) versions that are installed on the development computer.
  4. Fill in the Application name, such as Example of Basic Activity.
  5. Fill in the Package name, such as com.cookbook.simple_activity.
  6. To create the main activity in the same step, be sure Create Activity is checked and fill in an Activity name, such as SimpleActivity.
All activities extend the abstract class Activity or one of its subclasses.The entry point to each activity is the onCreate() method. It is almost always overridden to initialize the activity, such as setting up the UI, creating button listeners, initializing parameters, and starting threads. If the main activity is not created with the project or another activity needs to be added, the steps to create an activity are
  1. Create a class to extend Activity. (In Eclipse, this can be done by right-clicking on the project, choosing New → Class, and then specifying android.app. Activity as the super class.)
  2. Override the onCreate() function. (In Eclipse, this can be done by right-clicking on the class file, choosing Source → Override/Implement Methods..., and then checking the onCreate() method.)
  3. As with most overridden functions, it must invoke the super class method, too; otherwise, an exception may be thrown at run-time. Here, the super.onCreate() should be called first to properly initialize the activity, as shown in Listing 1.1. 
Simple Activity coding developer android
Images 1.1 Simple Activity

4. If a UI is used, specify the layout in an XML file in the res/layout/ directory. Here it is called main.xml, as shown in Listing 1.2.
5. Set the layout of the activity using the setContentView() function and passing it the resource ID for the XML layout file. Here, it is R.layout.main, as shown in Listing 2.1.
main xml coding android development
Images 1.2 Main.xml


6. Declare the properties of the activity in the AndroidManifest XML file.This is covered in more detail in Listing 2.5.
Note that the string resources are defined in the strings.xml file in the res/values/folder, as shown in Listing 2.3.This provides a central place for all strings in case text needs to be changed or reused.
strings xml
Images 1.3 String.xml
Now a more detailed look at the directory structure of this project and the additional auto-generated content is explored.


0 komentar:

Posting Komentar