【Android Drawable系列】- 封装ShapeBut
2018-12-24 本文已影响17人
MrTrying
Android Drawable系列
其实ShapeButton的封装主要就是对GradientDrawable和自己定义属性的封装,方便在开发中的使用,比较简单的圆角、描边一类的背景可以直接在xml中达到效果,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方法中进行相关属性的设置
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//默认设置矩形
mNormalBackgroundDrawable.setShape(GradientDrawable.RECTANGLE);
//设置背景色
mNormalBackgroundDrawable.setColor(mBackgroundColor);
//设置圆角
mNormalBackgroundDrawable.setCornerRadii(getCornerRadii());
//设置描边
setNormalDrawableStroke()
setBackgroundDrawable(mNormalBackgroundDrawable);
}
/**设置描边*/
private void setNormalDrawableStroke() {
if (mStrokeColor != 0 && mStrokeWidth > 0) {
mNormalBackgroundDrawable.setStroke(mStrokeWidth, mStrokeColor, mStrokeDashWidth, mStrokeDashGap);
}
}
到这里主要代码已经ok了,剩下的就是一些方便使用的方法扩展了。