20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A Closer Look at <strong>Android</strong> Activities x 87<br />

To assign a UI to an Activity, call setContentView from the onCreate method of your Activity.<br />

In this first snippet, an instance of a TextView is used as the Activity’s UI:<br />

@Override<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

TextView textView = new TextView(this);<br />

setContentView(textView);<br />

}<br />

Usually, you’ll want to use a more complex UI design. You can create a layout in code using layout<br />

View Groups, or you can use the standard <strong>Android</strong> convention of passing a resource ID for a<br />

layout defined in an external resource, as shown in the following snippet:<br />

@Override<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

setContentView(R.layout.main);<br />

}<br />

To use an Activity in your application, you need to register it in the manifest. Add a new<br />

activity tag within the application node of the manifest; the activity tag includes attributes<br />

for metadata, such as the label, icon, required permissions, and themes used by the Activity. An<br />

Activity without a corresponding activity tag can’t be displayed — attempting to do so will<br />

result in a runtime exception.<br />

<br />

<br />

Within the activity tag you can add intent-filter nodes that specify the Intents that can be<br />

used to start your Activity. Each Intent Filter defines one or more actions and categories that your<br />

Activity supports. Intents and Intent Filters are covered in depth in Chapter 5, but it’s worth noting<br />

that for an Activity to be available from the application launcher, it must include an Intent<br />

Filter listening for the MAIN action and the LAUNCHER category, as highlighted in Listing 3-10.<br />

LISTING 3-10: Main <strong>Application</strong> Activity Definition<br />

<br />

<br />

<br />

<br />

<br />

<br />

code snippet PA4AD_Ch03_Activities/<strong>Android</strong>Manifest.xml<br />

The Activity Lifecycle<br />

A good understanding of the Activity lifecycle is vital to ensure that your application provides a<br />

seamless user experience and properly manages its resources.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!