【Android|【Android Drawable系列】- 封装ShapeButton
文章图片
Android Drawable系列 其实ShapeButton的封装主要就是对GradientDrawable和自己定义属性的封装,方便在开发中的使用,比较简单的圆角、描边一类的背景可以直接在xml中达到效果,java代码中也方便修改。
需要定义的属性主要就是背景色、圆角和描边的属性,如下:
然后在让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了,剩下的就是一些方便使用的方法扩展了。
【【Android|【Android Drawable系列】- 封装ShapeButton】源码地址
推荐阅读
- 宽容谁
- 我要做大厨
- android第三方框架(五)ButterKnife
- 增长黑客的海盗法则
- 画画吗()
- 2019-02-13——今天谈梦想()
- 远去的风筝
- 三十年后的广场舞大爷
- 叙述作文
- 20190302|20190302 复盘翻盘