Rolling Your Own Widgets

As mentioned earlier, "widget" is a just convenient term for a subclass of android.view.View, typically for a leaf node in the view tree. Many views are just containers for other views and are used for layout; we don't consider them widgets, because they don't directly interact with the user, handle events, etc. So the term "widget," although informal, is useful for discussing the workhorse parts of the user interface that have the information and the behavior users care about.

You can accomplish a lot without creating a new widget. Chapter 11 constructed applications consisting entirely of existing widgets or simple subclasses of existing widgets. The code in that chapter demonstrated building trees of views, laying them out in code or in layout resources in XML files.

Similarly, the MicroJobs application has a view that contains a list of names corresponding to locations on a map. As additional locations are added to the map, new name-displaying widgets are added dynamically to the list. Even this dynamically changing layout is just a use of pre-existing widgets; it does not create new ones. The techniques in MicroJobs are, figuratively, adding or removing boxes from a tree like the one illustrated in Figure 10-3 in Chapter 10.

In contrast, this chapter shows you how to roll your own widget, which involves looking under the View hood.

The simplest customizations start with TextView, Button, DatePicker, or one of the many widgets presented in the previous chapter. For more extensive customization, you will implement your own widget as a direct subclass of View.

A very complex widget, perhaps used as an interface tool implemented in several places (even by multiple applications), might even be an entire package of classes, only one of which is a descendant of View.

This chapter is about graphics, and therefore about the View part of the Model-View-Controller pattern. Widgets also contain Controller code, which is good design because it keeps together all of the code relevant to a behavior and its representation on the screen. This part of this chapter discusses only the implementation of the View; the implementation of the Controller was discussed in Chapter 10.

Concentrating on graphics, then, we can break the tasks of this chapter into two essential parts: finding space on the screen and drawing in that space. The first task is known as layout. A leaf widget can assert its space needs by defining an onMeasure method that the Android framework will call at the right time. The second task, actually rendering the widget, is handled by the widget's onDraw method.

0 0

Post a comment