1、GradientDrawable 的静态使用
项目中我们常用的是GradientDrawable 的静态使用即在xml中使用shape标签定义,这也是我们常用的
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="3dp"></corners>
<gradient
android:centerColor="@color/color_ffffff"
android:endColor="@color/color_ffffff"
android:startColor="@color/color_ffffff"></gradient>
<solid android:color="@color/color_3699ff"></solid>
<stroke
android:width=""
android:dashWidth=""></stroke>
<padding
android:bottom=""
android:left=""></padding>
<size android:width=""></size>
</shape>
2、GradientDrawable 的动态用法,为了防止过多的创建xml还可以在代码中设置shape背景
1、基本属性设置
GradientDrawable bg = new GradientDrawable();
bg.setShape(shape);
bg.setStroke(lineWidth,lineColor,dashWidth,dashGap);
bg.setCornerRadius(cornerRadius);
bg.setColor(bkColor);
mTextView.setBackground(bg);
其中shepe属性有LINE 、OVAL、RECTANGLE、RING和xml的属性相对应。
2、除此之外我们还可以对其进项封装来方便使用
public class ShapeBuilder {
public Drawable build() {
final GradientDrawable bg = new GradientDrawable();
bg.setShape(shape);
bg.setStroke(lineWidth,lineColor,dashWidth,dashGap);
bg.setCornerRadius(cornerRadius);
bg.setColor(bkColor);
return bg;
}
public ShapeBuilder shape(int shape) {
this.shape = shape;
return this;
}
public ShapeBuilder line(int width,String color) {
return lineWidth(width).lineColor(color);
}
public ShapeBuilder lineWidth(int lineWidth) {
this.lineWidth = DeviceInfo.convertDpToPx(lineWidth);
return this;
}
public ShapeBuilder lineColor(int lineColor) {
this.lineColor = lineColor;
return this;
}
public ShapeBuilder corner(float cornerRadius) {
this.cornerRadius = DeviceInfo.convertDpToPx(cornerRadius);
return this;
}
public ShapeBuilder corner() {
return corner(defaultCornerRadius);
}
public ShapeBuilder dash() {
return dashWidth(defaultDashWidth).dashGap(defaultDashGap);
}
}
通过链式点的方式对其进行初始化。