以下是几种实现自定义可选 / 按钮控件的方式:
方式一:继承并扩展现有的控件
可以通过扩展现有的可选 / 按钮控件来创建自定义控件。例如,扩展Checkbox或RadioButton类。以下是扩展CheckBox类的示例代码:
public class MyCheckBox extends AppCompatCheckBox {
public MyCheckBox(Context context) {
super(context);
init();
}
public MyCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setButtonDrawable(getButtonDrawable().getConstantState().newDrawable());
}
}
注意init()方法的实现,该方法会复制原始状态的按钮drawable并应用到控件中。
方式二:使用StateListDrawable
可以使用StateListDrawable来创建自定义可选 / 按钮控件。以下是示例代码:
然后将StateListDrawable设置为你的可选 / 按钮控件的背景资源:
方式三:自定义Drawable
可以自定义Drawable来创建自定义可选 / 按钮控件。以下是示例代码:
public class CustomCheckedDrawable extends Drawable implements Checkable {
private boolean mChecked = false;
private Paint mPaint;
public CustomCheckedDrawable() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);