android自定义按钮android:shap,【Android Drawable系列】- 封装ShapeButton

75025762fa3a?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

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了,剩下的就是一些方便使用的方法扩展了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值