Android自定义Shape 加上阴影shadow之方法
Android支持自定义Shape, 以画出需要的形状,可以作为TextView, EditText, Button的背景drawable资源。Shape很简单,就是一个XML文件,SDK文档里描述其格式如下:
?
?
其支持的属性没有shadow, 做Web前端开发的同学写CSS可以很方便地加一个shadow属性值,如何给Android Shape加一个shadow,以得到类似的效果呢?
?
答案是使用layer-list !?? 直接上代码如下:
?
?
将以上xml存成btn_test, 放到res/drawable/目录下。 将该drawable xml设为一个TextView的backgroiund,
?
??
其效果如下图所示:
?
?
?
关于layer-list的进一步解释见SDK文档,如下:
?
?
Layer ListA
LayerDrawable
is a drawable objectthat manages an array of other drawables. Each drawable in the list is drawn in the order of thelist—the last drawable in the list is drawn on top.Each drawable is represented by an
file location:<item>
element inside a single<layer-list>
element.res/drawable/filename.xml
The filename is used as the resource ID.compiled resource datatype:Resource pointer to aLayerDrawable
.resource reference:In Java:R.drawable.filename
In XML:@[package:]drawable/filename
syntax:?
?
elements:<layer-list>
Required. This must be the root element. Contains one or more<item>
elements.?
To avoid scaling, the following example uses a
<bitmap>
element with centeredgravity:?example:XML file saved atres/drawable/layers.xml
:Notice that this example uses a nested
<bitmap>
element to define the drawableresource for each item with a "center" gravity. This ensures that none of the images are scaled tofit the size of the container, due to resizing caused by the offset images.This layout XML applies the drawable to a View:
?
This layout XML applies the drawable to a View:
?
?The result is a stack of increasingly offset images:
see also:
LayerDrawable
?