Android 自定义圆角布局

in 大杂烩 with 0 comments, 3278 views

需求

由于最近项目当中需要用到的圆角空间比较多,以前是采用shape xml文件来实现(还不知道该方法的小伙伴,请自行查阅相关资料,由于比较简单,这里便不再详解),但是该方式有一个缺点,如果控件的背景颜色需要更改,那么就需要增加一个xml文件,不能实现动态更改,于是我想到了采用自定义布局的方式来实现圆角控件

思路

根据shape 的经验,发现只需要将控件的背景改变成圆角的,即可实现圆角控件,其实就是将xml实现的内容,在代码中实现

代码

float[] outerR = new float[]{mRadius, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius, mRadius};
RoundRectShape roundRectShape = new RoundRectShape(outerR, null, null);
ShapeDrawable shapeDrawable = new ShapeDrawable(roundRectShape);
shapeDrawable.getPaint().setColor(mBgColor);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setAntiAlias(true);
super.setBackgroundDrawable(shapeDrawable);

上面代码是设置圆角背景关键代码

自定义属性

由于需要动态修改背景颜色,于是我们需要首先自定义属性

<declare-styleable name="roundview">
    <attr name="corner_size" format="dimension" />
    <attr name="roundview_background" format="color|reference" />
    <attr name="roundview_text" format="string|reference" />
</declare-styleable>
mBgColor = typedArray.getColor(R.styleable.roundview_roundview_background, Color.RED);

代码已经上传,免积分下载地址:下载地址

Responses ${replyToWho} / Cancel Reply