To create a new activity, you must inherit the activity class, define the UI, and implement functions. The basic framework code of the new activity is as follows:
Package com. paad. myapplication;
Import Android. App. activity;
Import Android. OS. Bundle;
Public class myactivity extends activity {
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle icicle ){
Super. oncreate (icicle );
}
}
The basic activity class represents an empty screen, which is useless. Therefore, the first thing to do is to fill the UI with views and layouts.
The UI of the activity is created by views. Views is a UI control that displays data and provides user interaction. Android provides some layout classes called view groups, which can accommodate multiple views to help you design complex UIS.
In Chapter 4th, we will describe view and view groups in detail, and explain what is available, how to use it, and how to create custom views and layouts.
Specify the UI for the activity. Call the setcontentview method in the oncreate method of the activity.
In this code snippet, a simple example of myview is used as the UI of the activity:
@ Override
Public void oncreate (bundle icicle ){
Super. oncreate (icicle );
Myview = new myview (this );
Setcontentview (myview );
}
In most cases, you want to use a more complex UI design. You can use view groups in the code to create a layout, or you can use the convenience of standard android to transmit a resource ID of the externally defined layout, as shown in the following code snippet:
@ Override
Public void oncreate (bundle icicle ){
Super. oncreate (icicle );
Setcontentview (R. layout. Main );
}
To use an activity in an application, You need to register it in manifest. Add a new activity tag to the application node. The activity contains metadata such as label, icon, permissions, and themes. Activity without corresponding activity tags cannot be started.
The following XML snippet shows how to add a node to the myactivity class I just created:
<Activity Android: Label = "@ string/app_name"
Android: Name = ". myactivity">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Main"/>
<Category Android: Name = "android. Intent. Category. launcher"/>
</Intent-filter>
</Activity>
In the activity tag, you can add an intent-filter node to indicate the intent of your activity listening and response. Each intent filter can define one or more actions and categories. Intent and intent filters are described in detail in chapter 5th, but they have no value for an activity as the main Startup Program. It must contain an intent filter to listen to the main action and launcher type, as shown in the following high-brightness code snippet:
<Activity Android: Label = "@ string/app_name"
Android: Name = ". myactivity">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Main"/>
<Category Android: Name = "android. Intent. Category. launcher"/>
</Intent-filter>
</Activity>