Creating Your First Activity
You may have already created your first activity if you created a project using the New Android Project Wizard in Chapter 3: the MainActivity
activity. Open the MainActivity.java
file in your project to enhance it in the following sections.
Starting with onCreate
The entry point into your application is the onCreate()
method. The code for the MainActivity.java
file already contains an implementation of the onCreate()
method. It’s where you start writing code! For now, your code should look like this:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
}
}
You write the initialization code directly below the setContentView()
method.
super.onCreate(savedInstanceState);
It’s required for the application to run. This line directs the base Activity
class to perform setup work for the MainActivity
class. If you omit this line of code, you receive a runtime exception.
Telling Android to display the user interface
By default, an activity has no idea what its user interface is. It can be a simple form that allows the user to type information to be saved; a visual, camera-based, augmented, virtual reality application ...
Get Android Application Development For Dummies, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.