Drawable Resources

来源:互联网 发布:java线程停止 编辑:程序博客网 时间:2024/04/29 15:38

Drawable Resources

See also

  1. 2D Graphics

A drawable resource is a general concept for a graphic that canbe drawn to the screen and which you can retrieve with APIs such asgetDrawable(int) or apply to another XML resource withattributes such as android:drawable andandroid:icon. There are several different types ofdrawables:

Bitmap File

A bitmap graphic file (.png, .jpg, or.gif). Creates aBitmapDrawable.
Nine-Patch File
A PNG file with stretchable regions to allow image resizingbased on content (.9.png). Creates aNinePatchDrawable.
Layer List
A Drawable that manages an array of other Drawables. These aredrawn in array order, so the element with the largest index is bedrawn on top. Creates aLayerDrawable.
State List
An XML file that references different bitmap graphics fordifferent states (for example, to use a different image when abutton is pressed). Creates aStateListDrawable.
Level List
An XML file that defines a drawable that manages a number ofalternate Drawables, each assigned a maximum numerical value.Creates aLevelListDrawable.
Transition Drawable
An XML file that defines a drawable that can cross-fade betweentwo drawable resources. Creates aTransitionDrawable.
Inset Drawable
An XML file that defines a drawable that insets anotherdrawable by a specified distance. This is useful when a View needsa background drawble that is smaller than the View's actualbounds.
Clip Drawable
An XML file that defines a drawable that clips another Drawablebased on this Drawable's current level value. Creates aClipDrawable.
Scale Drawable
An XML file that defines a drawable that changes the size ofanother Drawable based on its current level value. Creates aScaleDrawable
Shape Drawable
An XML file that defines a geometric shape, including colorsand gradients. Creates aShapeDrawable.

Also see the Animation Resource document for how to create an AnimationDrawable.

Note: A color resource can also be used as a drawable in XML. Forexample, when creating astate list drawable, you can reference a color resource for theandroid:drawable attribute(android:drawable="@color/green").

Bitmap

A bitmap image. Android supports bitmap files in a threeformats: .png (preferred),.jpg(acceptable), .gif (discouraged).

You can reference a bitmap file directly, using the filename asthe resource ID, or create an alias resource ID in XML.

Note: Bitmap files may beautomatically optimized with lossless image compression by theaapt tool. For example, a true-color PNG that does not requiremore than 256 colors may be converted to an 8-bit PNG with a colorpalette. This will result in an image of equal quality but whichrequires less memory. So be aware that the image binaries placed inthis directory can change during the build. If you plan on readingan image as a bit stream in order to convert it to a bitmap, putyour images in theres/raw/ folder instead, where theywill not be optimized.

Bitmap File

A bitmap file is a .png, .jpg, or.gif file. Android creates aDrawable resource for any of these files when you savethem in the res/drawable/ directory.

file location:
res/drawable/filename.png(.png, .jpg, or.gif)
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a BitmapDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
example:
With an image saved at res/drawable/myimage.png,this layout XML applies the image to a View:
<ImageView    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:src="@drawable/myimage" />

The following application code retrieves the image as aDrawable:

Resources res = getResources();Drawable drawable = res.getDrawable(R.drawable.myimage);
see also:
  • 2D Graphics
  • BitmapDrawable

XML Bitmap

An XML bitmap is a resource defined in XML that points to abitmap file. The effect is an alias for a raw bitmap file. The XMLcan specify additional properties for the bitmap such as ditheringand tiling.

Note: You can use a<bitmap> element as achild of an<item>element. For example, when creating a state list or layer list, you can exclude the android:drawableattribute from an<item>element and nest a<bitmap> inside it thatdefines the drawable item.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a BitmapDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><bitmap    xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@[package:]drawable/drawable_resource"    android:antialias=["true" | "false"   android:dither=["true" | "false"   android:filter=["true" | "false"   android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical"                     "fill_vertical" | "center_horizontal" | "fill_horizontal"                     "center" | "fill" | "clip_vertical" | "clip_horizontal"   android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />
elements:
<bitmap>
Defines the bitmap source and its properties.

attributes:

xmlns:android
String. Defines the XML namespace, which must be"http://schemas.android.com/apk/res/android". This isrequired only if the<bitmap> is the rootelement—it is not needed when the<bitmap> is nestedinside an<item>.
android:src
Drawable resource. Required.Reference to a drawable resource.
android:antialias
Boolean. Enables or disables antialiasing.
android:dither
Boolean. Enables or disables dithering of the bitmapif the bitmap does not have the same pixel configuration as thescreen (for instance: a ARGB 8888 bitmap with an RGB 565screen).
android:filter
Boolean. Enables or disables bitmap filtering.Filtering is used when the bitmap is shrunk or stretched to smoothits apperance.
android:gravity
Keyword. Defines the gravity for the bitmap. Thegravity indicates where to position the drawable in its containerif the bitmap is smaller than the container.

Must be one or more (separated by '|') of the following constantvalues:

ValueDescriptiontopPut the object at the top of its container, not changing itssize.bottomPut the object at the bottom of its container, not changing itssize.leftPut the object at the left edge of its container, not changingits size.rightPut the object at the right edge of its container, not changingits size.center_verticalPlace object in the vertical center of its container, notchanging its size.fill_verticalGrow the vertical size of the object if needed so it completelyfills its container.center_horizontalPlace object in the horizontal center of its container, notchanging its size.fill_horizontalGrow the horizontal size of the object if needed so itcompletely fills its container.centerPlace the object in the center of its container in both thevertical and horizontal axis, not changing its size.fillGrow the horizontal and vertical size of the object if neededso it completely fills its container. This is the default.clip_verticalAdditional option that can be set to have the top and/or bottomedges of the child clipped to its container's bounds. The clip isbased on the vertical gravity: a top gravity clips the bottom edge,a bottom gravity clips the top edge, and neither clips bothedges.clip_horizontalAdditional option that can be set to have the left and/or rightedges of the child clipped to its container's bounds. The clip isbased on the horizontal gravity: a left gravity clips the rightedge, a right gravity clips the left edge, and neither clips bothedges.
android:tileMode
Keyword. Defines the tile mode. When the tile mode isenabled, the bitmap is repeated. Gravity is ignored when the tilemode is enabled.

Must be one of the following constant values:

ValueDescriptiondisabledDo not tile the bitmap. This is the default value.clampReplicates the edge color if the shader draws outside of itsoriginal boundsrepeatRepeats the shader's image horizontally and vertically.mirrorRepeats the shader's image horizontally and vertically,alternating mirror images so that adjacent images always seam.
example:
<?xml version="1.0" encoding="utf-8"?><bitmap xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@drawable/icon"    android:tileMode="repeat" />
see also:
  • BitmapDrawable
  • Creating alias resources

Nine-Patch

A NinePatch is a PNG image in which you can definestretchable regions that Android scales when content within theView exceeds the normal image bounds. You typically assign thistype of image as the background of a View that has at least onedimension set to"wrap_content", and when the Viewgrows to accomodate the content, the Nine-Patch image is alsoscaled to match the size of the View. An example use of aNine-Patch image is the background used by Android's standardButton widget, which must stretch to accommodate thetext (or image) inside the button.

Same as with a normal bitmap, you can reference a Nine-Patch file directly or from aresource defined by XML.

For a complete discussion about how to create a Nine-Patch filewith stretchable regions, see the2D Graphics document.

Nine-Patch File

file location:
res/drawable/filename.9.png
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a NinePatchDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
example:
With an image saved atres/drawable/myninepatch.9.png, this layout XMLapplies the Nine-Patch to a View:
<Button    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:background="@drawable/myninepatch" />
see also:
  • 2D Graphics
  • NinePatchDrawable

XML Nine-Patch

An XML Nine-Patch is a resource defined in XML that points to aNine-Patch file. The XML can specify dithering for the image.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a NinePatchDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><nine-patch    xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@[package:]drawable/drawable_resource"    android:dither=["true" | "false"] />
elements:
<nine-patch>
Defines the Nine-Patch source and its properties.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:src
Drawable resource. Required.Reference to a Nine-Patch file.
android:dither
Boolean. Enables or disables dithering of the bitmapif the bitmap does not have the same pixel configuration as thescreen (for instance: a ARGB 8888 bitmap with an RGB 565screen).
example:
<?xml version="1.0" encoding="utf-8"?><nine-patch xmlns:android="http://schemas.android.com/apk/res/android"    android:src="@drawable/myninepatch"    android:dither="false" />

Layer List

A LayerDrawable is a drawable object that manages an arrayof other drawables. Each drawable in the list is drawn in the orderof the list—the last drawable in the list is drawn on top.

Each drawable is represented by an<item> element inside asingle <layer-list>element.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a LayerDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><layer-list    xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:drawable="@[package:]drawable/drawable_resource"        android:id="@[+][package:]id/resource_name"        android:top="dimension"        android:right="dimension"        android:bottom="dimension"        android:left="dimension" /></layer-list>
elements:
<layer-list>
Required. This must be the root element.Contains one or more<item> elements.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
<item>
Defines a drawable to place in the layer drawable, in aposition defined by its attributes. Must be a child of a<selector> element.Accepts child<bitmap>elements.

attributes:

android:drawable
Drawable resource. Required.Reference to a drawable resource.
android:id
Resource ID. A unique resource ID for this drawable.To create a new resource ID for this item, use the form:"@+id/name". The plus symbol indicates thatthis should be created as a new ID. You can use this identifier toretrieve and modify the drawable with View.findViewById() orActivity.findViewById().
android:top
Integer. The top offset in pixels.
android:right
Integer. The right offset in pixels.
android:bottom
Integer. The bottom offset in pixels.
android:left
Integer. The left offset in pixels.

All drawable items are scaled to fit the size of the containingView, by default. Thus, placing your images in a layer list atdifferent positions might increase the size of the View and someimages scale as appropriate. To avoid scaling items in the list,use a <bitmap> elementinside the <item>element to specify the drawable and define the gravity to somethingthat does not scale, such as"center". For example,the following <item>defines an item that scales to fit its container View:

<item android:drawable="@drawable/image" />

To avoid scaling, the following example uses a<bitmap> element withcentered gravity:

<item>  <bitmap android:src="@drawable/image"          android:gravity="center" /></item>
example:
XML file saved at res/drawable/layers.xml:
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">    <item>      <bitmap android:src="@drawable/android_red"        android:gravity="center" />    </item>    <item android:top="10dp" android:left="10dp">      <bitmap android:src="@drawable/android_green"        android:gravity="center" />    </item>    <item android:top="20dp" android:left="20dp">      <bitmap android:src="@drawable/android_blue"        android:gravity="center" />    </item></layer-list>

Notice that this example uses a nested<bitmap> element todefine the drawable resource for each item with a "center" gravity.This ensures that none of the images are scaled to fit the size ofthe container, due to resizing caused by the offset images.

This layout XML applies the drawable to a View:

<ImageView    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:src="@drawable/layers" />

The result is a stack of increasingly offset images:

see also:
  • LayerDrawable

State List

A StateListDrawable is a drawable object defined in XMLthat uses a several different images to represent the same graphic,depending on the state of the object. For example, aButton widget can exist in one of several differentstates (pressed, focused, or niether) and, using a state listdrawable, you can provide a different background image for eachstate.

You can describe the state list in an XML file. Each graphic isrepresented by an<item>element inside a single<selector> element. Each<item> uses variousattributes to describe the state in which it should be used as thegraphic for the drawable.

During each state change, the state list is traversed top tobottom and the first item that matches the current state isused—the selection isnot based on the "best match," butsimply the first item that meets the minimum criteria of thestate.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a StateListDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"    android:constantSize=["true" | "false"   android:dither=["true" | "false"   android:variablePadding=["true" | "false"] >    <item        android:drawable="@[package:]drawable/drawable_resource"        android:state_pressed=["true" | "false"       android:state_focused=["true" | "false"       android:state_selected=["true" | "false"       android:state_checkable=["true" | "false"       android:state_checked=["true" | "false"       android:state_enabled=["true" | "false"       android:state_window_focused=["true" | "false"] /></selector>
elements:
<selector>
Required. This must be the root element.Contains one or more<item> elements.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:constantSize
Boolean. "true" if the drawable's reported internalsize remains constant as the state changes (the size is the maximumof all of the states); "false" if the size varies based on thecurrent state. Default is false.
android:dither
Boolean. "true" to enable dithering of the bitmap ifthe bitmap does not have the same pixel configuration as the screen(for instance, an ARGB 8888 bitmap with an RGB 565 screen); "false"to disable dithering. Default is true.
android:variablePadding
Boolean. "true" if the drawable's padding shouldchange based on the current state that is selected; "false" if thepadding should stay the same (based on the maximum padding of allthe states). Enabling this feature requires that you deal withperforming layout when the state changes, which is often notsupported. Default is false.
<item>
Defines a drawable to use during certain states, as describedby its attributes. Must be a child of a<selector> element.

attributes:

android:drawable
Drawable resource. Required.Reference to a drawable resource.
android:state_pressed
Boolean. "true" if this item should be used when theobject is pressed (such as when a button is touched/clicked);"false" if this item should be used in the default, non-pressedstate.
android:state_focused
Boolean. "true" if this item should be used when theobject is focused (such as when a button is highlighted using thetrackball/d-pad); "false" if this item should be used in thedefault, non-focused state.
android:state_selected
Boolean. "true" if this item should be used when theobject is selected (such as when a tab is opened); "false" if thisitem should be used when the object is not selected.
android:state_checkable
Boolean. "true" if this item should be used when theobject is checkable; "false" if this item should be used when theobject is not checkable. (Only useful if the object can transitionbetween a checkable and non-checkable widget.)
android:state_checked
Boolean. "true" if this item should be used when theobject is checked; "false" if it should be used when the object isun-checked.
android:state_enabled
Boolean. "true" if this item should be used when theobject is enabled (capable of receiving touch/click events);"false" if it should be used when the object is disabled.
android:state_window_focused
Boolean. "true" if this item should be used when theapplication window has focus (the application is in theforeground), "false" if this item should be used when theapplication window does not have focus (for example, if thenotification shade is pulled down or a dialog appears).

Note: Remember that Androidapplies the first item in the state list that matches the currentstate of the object. So, if the first item in the list containsnone of the state attributes above, then it is applied every time,which is why your default value should always be last (asdemonstrated in the following example).

example:
XML file saved at res/drawable/button.xml:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"          android:drawable="@drawable/button_pressed" /> <!-- pressed -->    <item android:state_focused="true"          android:drawable="@drawable/button_focused" /> <!-- focused -->    <item android:drawable="@drawable/button_normal" /> <!-- default --></selector>

This layout XML applies the state list drawable to a Button:

<Button    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:background="@drawable/button" />
see also:
  • StateListDrawable

Level List

A Drawable that manages a number of alternate Drawables, eachassigned a maximum numerical value. Setting the level value of thedrawable withsetLevel() loads the drawable resource in the level listthat has a android:maxLevel value greater than orequal to the value passed to the method.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a LevelListDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><level-list    xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:drawable="@drawable/drawable_resource"        android:maxLevel="integer"        android:minLevel="integer" /></level-list>
elements:
<level-list>
This must be the root element. Contains one or more<item> elements.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
<item>
Defines a drawable to use at a certain level.

attributes:

android:drawable
Drawable resource. Required.Reference to a drawable resource to be inset.
android:maxLevel
Integer. The maximum level allowed for this item.
android:minLevel
Integer. The minimum level allowed for this item.
example:
<?xml version="1.0" encoding="utf-8"?><level-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:drawable="@drawable/status_off"        android:maxLevel="0" />    <item        android:drawable="@drawable/status_on"        android:maxLevel="1" /></level-list>

Once this is applied to a View, the level can be changed withsetLevel() orsetImageLevel().

see also:
  • LevelListDrawable

Transition Drawable

A TransitionDrawable is a drawable object that cancross-fade between the two drawable resources.

Each drawable is represented by an<item> element inside asingle <transition>element. No more than two items are supported. To transitionforward, callstartTransition(). To transition backward, callreverseTransition().

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a TransitionDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><transitionxmlns:android="http://schemas.android.com/apk/res/android" >    <item        android:drawable="@[package:]drawable/drawable_resource"        android:id="@[+][package:]id/resource_name"        android:top="dimension"        android:right="dimension"        android:bottom="dimension"        android:left="dimension" /></transition>
elements:
<transition>
Required. This must be the root element.Contains one or more<item> elements.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
<item>
Defines a drawable to use as part of the drawable transition.Must be a child of a<transition> element.Accepts child<bitmap>elements.

attributes:

android:drawable
Drawable resource. Required.Reference to a drawable resource.
android:id
Resource ID. A unique resource ID for this drawable.To create a new resource ID for this item, use the form:"@+id/name". The plus symbol indicates thatthis should be created as a new ID. You can use this identifier toretrieve and modify the drawable with View.findViewById() orActivity.findViewById().
android:top
Integer. The top offset in pixels.
android:right
Integer. The right offset in pixels.
android:bottom
Integer. The bottom offset in pixels.
android:left
Integer. The left offset in pixels.
example:
XML file saved at res/drawable/transition.xml:
<?xml version="1.0" encoding="utf-8"?><transition xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/on" />    <item android:drawable="@drawable/off" /></transition>

This layout XML applies the drawable to a View:

<ImageButton    android:id="@+id/button"    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:src="@drawable/transition" />

And the following code performs a 500ms transition from thefirst item to the second:

ImageButton button = (ImageButton) findViewById(R.id.button);TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();drawable.startTransition(500);
see also:
  • TransitionDrawable

Inset Drawable

A drawable defined in XML that insets another drawable by aspecified distance. This is useful when a View needs a backgroundthat is smaller than the View's actual bounds.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a InsetDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><inset    xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/drawable_resource"    android:insetTop="dimension"    android:insetRight="dimension"    android:insetBottom="dimension"    android:insetLeft="dimension" />
elements:
<inset>
Defines the inset drawable. This must be the root element.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:drawable
Drawable resource. Required.Reference to a drawable resource to be inset.
android:insetTop
Dimension. The top inset, as a dimension value ordimension resource
android:insetRight
Dimension. The right inset, as a dimension value ordimension resource
android:insetBottom
Dimension. The bottom inset, as a dimension value ordimension resource
android:insetLeft
Dimension. The left inset, as a dimension value ordimension resource
example:
<?xml version="1.0" encoding="utf-8"?><inset xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/background"    android:insetTop="10dp"    android:insetLeft="10dp" />
see also:
  • InsetDrawable

Clip Drawable

A drawable defined in XML that clips another drawable based onthis Drawable's current level. You can control how much the childdrawable gets clipped in width and height based on the level, aswell as a gravity to control where it is placed in its overallcontainer. Most often used to implement things like progressbars.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a ClipDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><clip    xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/drawable_resource"    android:clipOrientation=["horizontal" | "vertical"   android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical"                    "fill_vertical" | "center_horizontal" | "fill_horizontal"                    "center" | "fill" | "clip_vertical" | "clip_horizontal"] />
elements:
<clip>
Defines the clip drawable. This must be the root element.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:drawable
Drawable resource. Required.Reference to a drawable resource to be clipped.
android:clipOrientation
Keyword. The orientation for the clip.

Must be one of the following constant values:

ValueDescriptionhorizontalClip the drawable horizontally.verticalClip the drawable vertically.
android:gravity
Keyword. Specifies where to clip within the drawable.

Must be one or more (separated by '|') of the following constantvalues:

ValueDescriptiontopPut the object at the top of its container, not changing itssize. When clipOrientation is "vertical",clipping occurs at the bottom of the drawable.bottomPut the object at the bottom of its container, not changing itssize. When clipOrientation is "vertical",clipping occurs at the top of the drawable.leftPut the object at the left edge of its container, not changingits size. This is the default. WhenclipOrientation is"horizontal", clipping occurs at the right side of thedrawable. This is the default.rightPut the object at the right edge of its container, not changingits size. WhenclipOrientation is"horizontal", clipping occurs at the left side of thedrawable.center_verticalPlace object in the vertical center of its container, notchanging its size. Clipping behaves the same as when gravity is"center".fill_verticalGrow the vertical size of the object if needed so it completelyfills its container. WhenclipOrientation is"vertical", no clipping occurs because the drawablefills the vertical space (unless the drawable level is 0, in whichcase it's not visible).center_horizontalPlace object in the horizontal center of its container, notchanging its size. Clipping behaves the same as when gravity is"center".fill_horizontalGrow the horizontal size of the object if needed so itcompletely fills its container. WhenclipOrientationis "horizontal", no clipping occurs because thedrawable fills the horizontal space (unless the drawable level is0, in which case it's not visible).centerPlace the object in the center of its container in both thevertical and horizontal axis, not changing its size. WhenclipOrientation is"horizontal", clippingoccurs on the left and right. When clipOrientation is"vertical", clipping occurs on the top andbottom.fillGrow the horizontal and vertical size of the object if neededso it completely fills its container. No clipping occurs becausethe drawable fills the horizontal and vertical space (unless thedrawable level is 0, in which case it's not visible).clip_verticalAdditional option that can be set to have the top and/or bottomedges of the child clipped to its container's bounds. The clip isbased on the vertical gravity: a top gravity clips the bottom edge,a bottom gravity clips the top edge, and neither clips bothedges.clip_horizontalAdditional option that can be set to have the left and/or rightedges of the child clipped to its container's bounds. The clip isbased on the horizontal gravity: a left gravity clips the rightedge, a right gravity clips the left edge, and neither clips bothedges.
example:
XML file saved at res/drawable/clip.xml:
<?xml version="1.0" encoding="utf-8"?><clip xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/android"    android:clipOrientation="horizontal"    android:gravity="left" /></clip>

The following layout XML applies the clip drawable to aView:

<ImageView    android:id="@+id/image"    android:background="@drawable/clip"    android:layout_height="wrap_content"    android:layout_width="wrap_content" />

The following code gets the drawable and increases the amount ofclipping in order to progressively reveal the image:

ImageView imageview = (ImageView) findViewById(R.id.image);ClipDrawable drawable = (ClipDrawable) imageview.getDrawable();drawable.setLevel(drawable.getLevel() + 1000);

Increasing the level reduces the amount of clipping and slowlyreveals the image. Here it is at a level of 7000:

Note: The default level is 0,which is fully clipped so the image is not visible. When the levelis 10,000, the image is not clipped and completely visible.

see also:
  • ClipDrawable

Scale Drawable

A drawable defined in XML that changes the size of anotherdrawable based on its current level.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a ScaleDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><scale    xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/drawable_resource"    android:scaleGravity=["top" | "bottom" | "left" | "right" | "center_vertical"                         "fill_vertical" | "center_horizontal" | "fill_horizontal"                         "center" | "fill" | "clip_vertical" | "clip_horizontal"   android:scaleHeight="percentage"    android:scaleWidth="percentage" />
elements:
<scale>
Defines the scale drawable. This must be the root element.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:drawable
Drawable resource. Required.Reference to a drawable resource.
android:scaleGravity
Keyword. Specifies the gravity position after scaling.

Must be one or more (separated by '|') of the following constantvalues:

ValueDescriptiontopPut the object at the top of its container, not changing itssize.bottomPut the object at the bottom of its container, not changing itssize.leftPut the object at the left edge of its container, not changingits size. This is the default.rightPut the object at the right edge of its container, not changingits size.center_verticalPlace object in the vertical center of its container, notchanging its size.fill_verticalGrow the vertical size of the object if needed so it completelyfills its container.center_horizontalPlace object in the horizontal center of its container, notchanging its size.fill_horizontalGrow the horizontal size of the object if needed so itcompletely fills its container.centerPlace the object in the center of its container in both thevertical and horizontal axis, not changing its size.fillGrow the horizontal and vertical size of the object if neededso it completely fills its container.clip_verticalAdditional option that can be set to have the top and/or bottomedges of the child clipped to its container's bounds. The clip isbased on the vertical gravity: a top gravity clips the bottom edge,a bottom gravity clips the top edge, and neither clips bothedges.clip_horizontalAdditional option that can be set to have the left and/or rightedges of the child clipped to its container's bounds. The clip isbased on the horizontal gravity: a left gravity clips the rightedge, a right gravity clips the left edge, and neither clips bothedges.
android:scaleHeight
Percentage. The scale height, expressed as apercentage of the drawable's bound. The value's format is XX%. Forinstance: 100%, 12.5%, etc.
android:scaleWidth
Percentage. The scale width, expressed as a percentageof the drawable's bound. The value's format is XX%. For instance:100%, 12.5%, etc.
example:
<?xml version="1.0" encoding="utf-8"?><scale xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/logo"    android:scaleGravity="center_vertical|center_horizontal"    android:scaleHeight="80%"    android:scaleWidth="80%" />
see also:
  • ScaleDrawable

Shape Drawable

This is a generic shape defined in XML.

file location:
res/drawable/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a ShapeDrawable.
resource reference:
In Java: R.drawable.filename
In XML:@[package:]drawable/filename
syntax:
<?xml version="1.0" encoding="utf-8"?><shape    xmlns:android="http://schemas.android.com/apk/res/android"    android:shape=["rectangle" | "oval" | "line" | "ring"] >    <corners        android:radius="integer"        android:topLeftRadius="integer"        android:topRightRadius="integer"        android:bottomLeftRadius="integer"        android:bottomRightRadius="integer" />    <gradient        android:angle="integer"        android:centerX="integer"        android:centerY="integer"        android:centerColor="integer"        android:endColor="color"        android:gradientRadius="integer"        android:startColor="color"        android:type=["linear" | "radial" | "sweep"       android:usesLevel=["true" | "false"] />    <padding        android:left="integer"        android:top="integer"        android:right="integer"        android:bottom="integer" />    <size        android:width="integer"        android:color="color"        android:dashWidth="integer"        android:dashGap="integer" />    <solid        android:color="color" />    <stroke        android:width="integer"        android:color="color"        android:dashWidth="integer"        android:dashGap="integer" /></shape>
elements:
<shape>
The shape drawable. This must be the root element.

attributes:

xmlns:android
String. Required. Defines the XMLnamespace, which must be"http://schemas.android.com/apk/res/android".
android:shape
Keyword. Defines the type of shape. Valid values are:ValueDesciption"rectangle"A rectangle that fills the containing View. This is the defaultshape."oval"An oval shape that fits the dimensions of the containingView."line"A horizontal line that spans the width of the containing View.This shape requires the<stroke> element todefine the width of the line."ring"A ring shape.

The following attributes are used only whenandroid:shape="ring":

android:innerRadius
Dimension. The radius for the inner part of the ring(the hole in the middle), as a dimension value ordimension resource.
android:innerRadiusRatio
Float. The radius for the inner part of the ring,expressed as a ratio of the ring's width. For instance, ifandroid:innerRadiusRatio="5", then the inner radiusequals the ring's width divided by 5. This value is overridden byandroid:innerRadius. Default value is 9.
android:thickness
Dimension. The thickness of the ring, as a dimensionvalue or dimension resource.
android:thicknessRatio
Float. The thickness of the ring, expressed as a ratioof the ring's width. For instance, ifandroid:thicknessRatio="2", then the thickness equalsthe ring's width divided by 2. This value is overridden byandroid:innerRadius. Default value is 3.
android:useLevel
Boolean. "true" if this is used as a LevelListDrawable. This should normally be "false" oryour shape may not appear.
<corners>
Creates rounded corners for the shape. Applies only when theshape is a rectangle.

attributes:

android:radius
Dimension. The radius for all corners, as a dimensionvalue or dimension resource. This is overridden for each corner by thefollowing attributes.
android:topLeftRadius
Dimension. The radius for the top-left corner, as adimension value ordimension resource.
android:topRightRadius
Dimension. The radius for the top-right corner, as adimension value ordimension resource.
android:bottomLeftRadius
Dimension. The radius for the bottom-left corner, as adimension value ordimension resource.
android:bottomRightRadius
Dimension. The radius for the bottom-right corner, asa dimension value ordimension resource.

Note: Every corner must(initially) be provided a corner radius greater than 1, or else nocorners are rounded. If you want specific corners tonotbe rounded, a work-around is to use android:radius toset a default corner radius greater than 1, but then override eachand every corner with the values you really want, providing zero("0dp") where you don't want rounded corners.

<gradient>
Specifies a gradient color for the shape.

attributes:

android:angle
Integer. The angle for the gradient, in degrees. 0 isleft to right, 90 is bottom to top. It must be a multiple of 45.Default is 0.
android:centerX
Float. The relative X-position for the center of thegradient (0 - 1.0). Does not apply whenandroid:type="linear".
android:centerY
Float. The relative Y-position for the center of thegradient (0 - 1.0). Does not apply whenandroid:type="linear".
android:centerColor
Color. Optional color that comes between the start andend colors, as a hexadecimal value orcolor resource.
android:endColor
Color. The ending color, as a hexadecimal value orcolor resource.
android:gradientRadius
Float. The radius for the gradient. Only applied whenandroid:type="radial".
android:startColor
Color. The starting color, as a hexadecimal value orcolor resource.
android:type
Keyword. The type of gradient pattern to apply. Validvalues are:ValueDescription"linear"A linear gradient. This is the default."radial"A radial gradient. The start color is the center color."sweep"A sweeping line gradient.
android:useLevel
Boolean. "true" if this is used as a LevelListDrawable.
<padding>
Padding to apply to the containing View element (this pads theposition of the View content, not the shape).

attributes:

android:left
Dimension. Left padding, as a dimension value ordimension resource.
android:top
Dimension. Top padding, as a dimension value ordimension resource.
android:right
Dimension. Right padding, as a dimension value ordimension resource.
android:bottom
Dimension. Bottom padding, as a dimension value ordimension resource.
<size>
The size of the shape.

attributes:

android:height
Dimension. The height of the shape, as a dimensionvalue or dimension resource.
android:width
Dimension. The width of the shape, as a dimensionvalue or dimension resource.

Note: The shape scales to the sizeof the container View proportionate to the dimensions defined here,by default. When you use the shape in anImageView, you can restrict scaling by setting theandroid:scaleType to "center".

<solid>
A solid color to fill the shape.

attributes:

android:color
Color. The color to apply to the shape, as ahexadecimal value or color resource.
<stroke>
A stroke line for the shape.

attributes:

android:width
Dimension. The thickness of the line, as a dimensionvalue or dimension resource.
android:color
Color. The color of the line, as a hexadecimal valueor color resource.
android:dashGap
Dimension. The distance between line dashes, as adimension value or dimension resource. Only valid ifandroid:dashWidth is set.
android:dashWidth
Dimension. The size of each dash line, as a dimensionvalue or dimension resource. Only valid if android:dashGapis set.
example:
XML file saved at res/drawable/gradient_box.xml:
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <gradient        android:startColor="#FFFF0000"        android:endColor="#80FF00FF"        android:angle="45"/>    <padding android:left="7dp"        android:top="7dp"        android:right="7dp"        android:bottom="7dp" />    <corners android:radius="8dp" /></shape>

This layout XML applies the shape drawable to a View:

<TextView    android:background="@drawable/gradient_box"    android:layout_height="wrap_content"    android:layout_width="wrap_content" />

This application code gets the shape drawable and applies it toa View:

Resources res = getResources();Drawable shape = res. getDrawable(R.drawable.gradient_box);TextView tv = (TextView)findViewByID(R.id.textview);tv.setBackground(shape);
0 0
原创粉丝点击