<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 填充的颜色 --> <solid android:color="#ffae00" /> <!-- 圆角的半径 --> <corners android:radius="10dp" /> </shape>
<widget.RoundCornerButton android:id="@+id/btn_commit" android:layout_width="100dp" android:layout_height="40dp" android:gravity="center" android:text="我的按钮" app:rcb_backgroundColor="@color/yellow" app:rcb_backgroundColorDisabled="@color/light_grey" app:rcb_cornerRadius="20dp" />
<declare-styleable name="RoundCornerButton"> <attr name="rcb_backgroundColor" format="color" /> <attr name="rcb_backgroundColorDisabled" format="color" /> <attr name="rcb_cornerRadius" format="dimension" /> </declare-styleable>
class RoundCornerDrawable extends Drawable {
final int color;
final float radius;
final Paint paint;
final RectF rectF;
RoundCornerDrawable(int color, float radius) {
this.color = color;
this.radius = radius;
// 实心的画笔
this.paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(color);
this.rectF = new RectF();
}
// 用于设置Drawable宽高
public void setRect(int width, int height) {
this.rectF.left = 0;
this.rectF.top = 0;
this.rectF.right = width;
this.rectF.bottom = height;
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawRoundRect(rectF, radius, radius, paint); // 画圆角矩形,现成的方法
}
// 其余方法略
}
public class RoundCornerButton extends AppCompatButton {
private int colorNormal;
private float cornerRadius;
private RoundCornerDrawable bgDrawableNormal = null;
// 省略三个构造方法
// 构造方法最后一定要调用initCornerBackground完成初始化
private void initCornerBackground(AttributeSet attrs, int defStyleAttr) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RoundCornerButton, defStyleAttr, 0);
this.cornerRadius = a.getDimension(R.styleable.RoundCornerButton_rcb_cornerRadius, 0);
this.colorNormal = a.getColor(R.styleable.RoundCornerButton_rcb_backgroundColor, 0);
makeBackgroundDrawable();
a.recycle();
}
private void makeBackgroundDrawable() {
bgDrawableNormal = new RoundCornerDrawable(this.colorNormal, this.cornerRadius);
bgDrawableNormal.setRect(getWidth(), getHeight());
// 设计通常会给出禁用时的样式以及按下时的样式
// 所以这里用使用StateListDrawable
StateListDrawable bgDrawable = new StateListDrawable();
bgDrawable.addState(new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed}, bgDrawableNormal);
// 每多一种状态,在这里多加一项
setBackgroundDrawable(bgDrawable);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// layout之后必然会draw,所以在这里设置drawable的尺寸
if (bgDrawableNormal != null) {
bgDrawableNormal.setRect(right - left, bottom - top);
}
// 每多一种状态,在这里多加一项
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有