Using Custom Controls

Having created your own custom Views, you can use them within code and layouts as you would any other View. Listing 4-15 shows you how to override the onCreate method in order to add the CompassView, created in the preceding example, to an Activity.

LISTING 4-15: Using a custom View

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CompassView cv = new CompassView(this); setContentView(cv);


To use the same control within a layout resource, specify the fully qualified class name when you create a new node in the layout definition, as shown in the following XML snippet.

<com.paad.compass.CompassView android:id="@+id/compassView"



You can inflate the layout and get a reference to the CompassView as usual, using the following code:

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

CompassView cv = (CompassView)this.findViewById(;


Available for download on


In Chapter 3 you were introduced to the resources framework and shown how to externalize your application resources and include alternative assets for different hardware platforms.

In this section you will be introduced to several new types of Drawables resources — including shapes and transformative and composite Drawables — and be shown how to use these resources to create user interfaces that are independent of screen size and resolution.

All of these resources can be defined and manipulated in code, but in this section we will focus on how to create these Drawables using XML.

The resources framework, described in Chapter 3, which can be used to define alternative resources for different hardware devices, can be used for all the XML Drawables described in this section.

Was this article helpful?

0 0
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