Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 31  Custom Views and Touch Events


Creating a Custom View


Android provides many excellent standard views and widgets, but sometimes you need a custom view
that presents visuals that are unique to your app.


While there are all kinds of custom views, you can shoehorn them into two broad categories:


simple A simple view may be complicated inside; what makes it “simple” is that it has no
child views. A simple view will almost always perform custom rendering.

composite Composite views are composed of other view objects. Composite views typically
manage child views but do not perform custom rendering. Instead, rendering is
delegated to each child view.

There are three steps to follow when creating a custom view:



  1. Pick a superclass. For a simple custom view, View is a blank canvas, so it is the most common
    choice. For a composite custom view, choose an appropriate layout class, such as FrameLayout.

  2. Subclass this class and override the constructors from the superclass.

  3. Override other key methods to customize behavior.


Creating BoxDrawingView


BoxDrawingView will be a simple view and a direct subclass of View.


Create a new class named BoxDrawingView and make View its superclass. In BoxDrawingView.java,
add two constructors.


Listing 31.3  Initial implementation for BoxDrawingView
(BoxDrawingView.java)


public class BoxDrawingView extends View {


// Used when creating the view in code
public BoxDrawingView(Context context) {
this(context, null);
}


// Used when inflating the view from XML
public BoxDrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}


You write two constructors because your view could be instantiated in code or from a layout file. Views
instantiated from a layout file receive an instance of AttributeSet containing the XML attributes
that were specified in XML. Even if you do not plan on using both constructors, it is good practice to
include them.

Free download pdf