
Android Drawable系列
其實ShapeButton的封裝主要就是對GradientDrawable和自己定義屬性的封裝,方便在開發(fā)中的使用,比較簡單的圓角、描邊一類的背景可以直接在xml中達(dá)到效果,java代碼中也方便修改。
需要定義的屬性主要就是背景色、圓角和描邊的屬性,如下:
<declare-styleable name="ShapeButton">
<!--背景色-->
<attr name="sBtn_backgroundColor" format="color"/>
<!--圓角-->
<attr name="sBtn_cornerRadius" format="dimension"/>
<attr name="sBtn_cornerRadii_topLeft" format="dimension"/>
<attr name="sBtn_cornerRadii_topRight" format="dimension"/>
<attr name="sBtn_cornerRadii_bottomLeft" format="dimension"/>
<attr name="sBtn_cornerRadii_bottomRight" format="dimension"/>
<attr name="sBtn_strokeColor" format="color"/>
<attr name="sBtn_strokeWidth" format="dimension"/>
<attr name="sBtn_strokeDashWidth" format="dimension"/>
<attr name="sBtn_strokeDashGap" format="dimension"/>
</declare-styleable>
然后在讓ShapeButton繼承AppCompatButton,并獲取xml中定義的屬性。
private void initialize(Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShapeButton);
mBackgroundColor = typedArray.getColor(R.styleable.ShapeButton_sBtn_backgroundColor, Color.TRANSPARENT);
mCornerRadius = typedArray.getDimension(R.styleable.ShapeButton_sBtn_cornerRadius, 0);
mCornerRadiiTopLeft = typedArray.getDimension(R.styleable.ShapeButton_sBtn_cornerRadii_topLeft, mCornerRadius);
mCornerRadiiTopRight = typedArray.getDimension(R.styleable.ShapeButton_sBtn_cornerRadii_topRight, mCornerRadius);
mCornerRadiiBottomRight = typedArray.getDimension(R.styleable.ShapeButton_sBtn_cornerRadii_bottomRight, mCornerRadius);
mCornerRadiiBottomLeft = typedArray.getDimension(R.styleable.ShapeButton_sBtn_cornerRadii_bottomLeft, mCornerRadius);
mStrokeColor = typedArray.getColor(R.styleable.ShapeButton_sBtn_strokeColor, 0);
mStrokeWidth = (int) typedArray.getDimension(R.styleable.ShapeButton_sBtn_strokeWidth, 0);
mStrokeDashWidth = typedArray.getDimension(R.styleable.ShapeButton_sBtn_strokeDashWidth, 0);
mStrokeDashGap = typedArray.getDimension(R.styleable.ShapeButton_sBtn_strokeDashGap, 0);
typedArray.recycle();
}
在onMeasure方法中進(jìn)行相關(guān)屬性的設(shè)置
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//默認(rèn)設(shè)置矩形
mNormalBackgroundDrawable.setShape(GradientDrawable.RECTANGLE);
//設(shè)置背景色
mNormalBackgroundDrawable.setColor(mBackgroundColor);
//設(shè)置圓角
mNormalBackgroundDrawable.setCornerRadii(getCornerRadii());
//設(shè)置描邊
setNormalDrawableStroke()
setBackgroundDrawable(mNormalBackgroundDrawable);
}
/**設(shè)置描邊*/
private void setNormalDrawableStroke() {
if (mStrokeColor != 0 && mStrokeWidth > 0) {
mNormalBackgroundDrawable.setStroke(mStrokeWidth, mStrokeColor, mStrokeDashWidth, mStrokeDashGap);
}
}
到這里主要代碼已經(jīng)ok了,剩下的就是一些方便使用的方法擴(kuò)展了。