Creating Activity User Interfaces with Views

A new Activity starts with a temptingly empty screen onto which you place your user interface. To assign the user interface, call setContentview, passing in the View instance, or layout resource, to display. Because empty screens aren't particularly inspiring, you will almost always use setContentview to assign an Activity's user interface when overriding its onCreate handler.

The setContentview method accepts either a layout resource ID (as described in Chapter 3) or a single View instance. This lets you define your user interface either in code or using the preferred technique of external layout resources.

Using layout resources decouples your presentation layer from the application logic, providing the flexibility to change the presentation without changing code. This makes it possible to specify different layouts optimized for different hardware configurations, even changing them at run time based on hardware changes (such as screen orientation).

Listing 4-1 shows how to set the user interface for an Activity using an external layout resource. You can get references to the Views used within a layout with the findviewByid method. This example assumes that main.xml exists in the project's res/layout folder.

LISTING 4-1: Inflating an Activity layout Available for download on ©Override public void onCreate(Bundle savedlnstanceState) super.onCreate(savedlnstanceState);


TextView myTextView = (TextView)findViewByld(;

If you prefer the more traditional approach, you can construct the user interface in code. Listing 4-2 shows how to assign a new TextView as the user interface.

LISTING 4-2: Creating a UI layout in code Available for download on @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

TextView myTextView = new TextView(this); setContentView(myTextView);

myTextView.setText("Hello, Android");

The setContentView method accepts a single View instance; as a result, you have to use layouts to add multiple controls to your Activity.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment