使用XML代码,自定义Button类和样式属性来实现自定义按钮。
首先,在XML布局文件中声明自定义Button类并设置样式属性,如下所示:
然后,在Java代码中实现自定义Button类,如下所示:
public class MyButton extends AppCompatButton {
private int backgroundColor;
private int textColor;
private float cornerRadius;
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyButton);
backgroundColor = ta.getColor(R.styleable.MyButton_backgroundColor, Color.BLUE);
textColor = ta.getColor(R.styleable.MyButton_textColor, Color.WHITE);
cornerRadius = ta.getDimension(R.styleable.MyButton_cornerRadius, 0);
ta.recycle();
setBackgroundColor(backgroundColor);
setTextColor(textColor);
setCornerRadius(cornerRadius);
}
public void setCornerRadius(float cornerRadius) {
this.cornerRadius = cornerRadius;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setElevation(4);
}
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(cornerRadius);
shape.setColor(backgroundColor);
setBackground(shape);
}
}
最后,在styles.xml中声明自定义样式属性,如下所示:
这样,在布局文件中使用MyButton类即可自定义按钮。