In Android, a Drawable class is used for a visual element like a bitmap or solid color that is intended for display only. You can combine drawables with other graphics, or you can use them in user interface widgets (for example, as the background for a button or view).

Drawables can take a variety of forms:

• NinePatch: A stretchable PNG image, so named because originally it divided the image into nine sections. These are used for the background of resizable bitmap buttons.

• Shape: Vector-drawing commands, based on Path. This is sort of a poor man's SVG.

• Layers: A container for child drawables that draw on top of each other in a certain z-order.

• States: A container that shows one of its child drawables based on its state (a bit mask). One use is to set various selection and focus states for buttons.

• Levels: A container that shows only one of its child drawables based on its level (a range of integers). This could be used for a battery or signal strength gauge.

• Scale: A container for one child drawable that modifies its size based on the current level. One use might be a zoomable picture viewer.

Drawables are often defined in XML. Here's a common example where a drawable is defined to be a gradient from one color to another (in this case, white to gray). The angle specifies the direction of the gradient (270 degrees means top to bottom). This will be used for the background of a view:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">

<gradient android:startColor="#FFFFFF" android:endColor="#808080" android:angle="270" /> </shape>

To use it, we could either refer to it in XML with the android:background= attribute or call the setBackgroundResource() method in the view's onCre-ate( ) method like this:


This gives our GraphicsView example a nice gradient background, as shown in Figure 4.2, on the next page.

Drawables should be placed in different directories depending on the screen density for which they are designed (see Section 3.4, Using Alternate Resources, on page 55).

aid ofthfy

0 0

Post a comment