@act262
2017-03-26T15:20:46.000000Z
字数 2095
阅读 1400
Android
使用 xml 定义的 shape 对应的是GradientDrawable,而ShapeDrawable是我们Java代码中常用到的,这2个没有相关关系。
drawable属性不支持直接使用颜色值,需要包装为ColorDrawable。可以用引用颜色值,或者增加一个<color>(ColorDrawable)子节点来设置颜色值。
// 编译错误<item android:drawable="#f00" />
改为值引用或者包装一层
<item android:drawable="@color/red" />
<item><color android:color="#f00" /></item>
具有多个样式的Drawable,用LayerDrawable组合多个Drawable
example:
<Viewandroid:layout_width="200dp"android:layout_height="100dp"android:layout_gravity="center"android:background="@drawable/bg_divider" />
如果4边框规可以直接用ShapeDrawable,规则是指都有边框,大小、颜色一样。
<shape xmlns:android="http://schemas.android.com/apk/res/android"><strokeandroid:width="1dp"android:color="#f00" /></shape>
不规则边框,可以用LayerDrawable来处理,同时需要注意LayerDrawable多层叠加导致的过度绘制,可以用padding、inset、gravity等属性设置位置关系。
例如需要做出顶部的边框或者顶部的分割线条效果
底色是红色,然后用白色盖住底色,距离顶部1dp,从而形成上边框1个dp的效果。
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item><color android:color="#f00" /></item><itemandroid:drawable="@android:color/white"android:top="1dp" /></layer-list>

多层颜色的覆盖会导致过度绘制,可以用下面的方式得到相同的效果而减少过度绘制
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@android:color/white"android:top="1dp" /><item android:height="1dp"> <!-- height/width API 23+才支持 --><color android:color="#f00" /></item></layer-list>
绘制一条线
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@android:color/white"android:top="1dp" /><item android:gravity="top"> <!-- 绘制一条线,需要设置gravity,不然会变成覆盖,且shape用的是矩形而不是line--><shape android:shape="rectangle"><solid android:color="#f00" /><size android:height="1dp" /></shape></item></layer-list>
也可以用白色来覆盖多余的边框,留下一条边框
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item><shape><strokeandroid:width="1dp"android:color="#f00" /></shape></item><itemandroid:drawable="@android:color/white"android:top="1dp" /></layer-list>
居中的线条
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@android:color/white"android:top="1dp" /><item><shape android:shape="line"><strokeandroid:width="1dp"android:color="#f00" /></shape></item></layer-list>
