要实现Android按钮叠加边框的自定义视图或矢量可绘制,可以使用以下步骤:
public class BorderButton extends Button {
public BorderButton(Context context) {
super(context);
init();
}
public BorderButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BorderButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置按钮的背景为空
setBackground(null);
// 设置按钮的文字颜色
setTextColor(getResources().getColor(android.R.color.black));
// 设置按钮的边框宽度和颜色
setStrokeWidth(2);
setStrokeColor(getResources().getColor(R.color.border_color));
}
private void setStrokeWidth(int width) {
GradientDrawable drawable = (GradientDrawable) getBackground();
if (drawable != null) {
drawable.setStroke(width, drawable.getStrokeColor());
}
}
private void setStrokeColor(int color) {
GradientDrawable drawable = (GradientDrawable) getBackground();
if (drawable != null) {
drawable.setStroke(drawable.getStrokeWidth(), color);
}
}
}
#FF0000
这样,你就可以创建一个带有叠加边框的自定义按钮视图。