Modifying Existing Views

The toolbox includes Views that provide many common UI requirements, but the controls are necessarily generic. By customizing these basic Views you avoid reimplementing existing behavior while still tailoring the user interface, and functionality, to your application's needs.

To create a new View based on an existing control, create a new class that extends it, as shown in Listing 4-5.

LISTING 4-5: Extending TextView Available for download on import android.content.Context; Wrox.com import android.util.AttributeSet;

import android.widget.TextView;

public class MyTextView extends TextView {

public MyTextView (Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

public MyTextView (Context context) { super(context);

public MyTextView (Context context, AttributeSet attrs) { super(context, attrs);

To override the appearance or behavior of your new View, override and extend the event handlers associated with the behavior you want to change.

In the following extension of the Listing 4-5 code, the onDraw method is overridden to modify the View's appearance, and the onKeyDown handler is overridden to allow custom key-press handling.

public class MyTextView extends TextView {

public MyTextView (Context context, AttributeSet ats, int defStyle) { super(context, ats, defStyle);

public MyTextView (Context context) { super(context);

public MyTextView (Context context, AttributeSet attrs) { super(context, attrs);

©Override public void onDraw(Canvas canvas) {

[ ... Draw things on the canvas under the text ... ]

// Render the text as usual using the TextView base class. super.onDraw(canvas);

[ ... Draw things on the canvas over the text ... ]

©Override public boolean onKeyDown(int keyCode, KeyEvent keyEvent) { [ ... Perform some special processing ... ] [ ... based on a particular key press ... ]

// Use the existing functionality implemented by // the base class to respond to a key press event, return super.onKeyDown(keyCode, keyEvent);

The event handlers available within Views are covered in more detail later in this chapter.

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