安卓自定义一个单选框,单选框里面包含文字,选中可以改变字体文字颜色,也可以改变单选框边框颜色
时间: 2024-04-28 22:19:35 浏览: 5
要自定义一个单选框(RadioButton),可以继承它的父类CompoundButton,然后在自定义类中实现需要改变字体文字颜色和单选框边框颜色的逻辑。
下面是一个示例代码:
```java
public class CustomRadioButton extends RadioButton {
private int mCheckedTextColor;
private int mUncheckedTextColor;
private int mCheckedBorderColor;
private int mUncheckedBorderColor;
public CustomRadioButton(Context context) {
super(context);
init();
}
public CustomRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mCheckedTextColor = Color.RED;
mUncheckedTextColor = Color.BLACK;
mCheckedBorderColor = Color.GREEN;
mUncheckedBorderColor = Color.GRAY;
}
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
if (checked) {
setTextColor(mCheckedTextColor);
setBorderColor(mCheckedBorderColor);
} else {
setTextColor(mUncheckedTextColor);
setBorderColor(mUncheckedBorderColor);
}
}
private void setBorderColor(int color) {
GradientDrawable drawable = (GradientDrawable) getBackground();
drawable.setStroke(2, color);
}
}
```
在上面的代码中,我们重写了setChecked()方法来实现选中和未选中时改变字体文字颜色和单选框边框颜色的逻辑。同时,我们还定义了四个变量来存储选中和未选中状态下的字体文字颜色和单选框边框颜色。
在init()方法中,我们初始化了这四个变量的默认值。
在setChecked()方法中,我们首先调用父类的setChecked()方法来实现选中状态的切换。然后,根据选中状态来设置字体文字颜色和单选框边框颜色。
最后,我们还实现了一个setBorderColor()方法来设置单选框边框颜色。这里我们使用了GradientDrawable类来绘制单选框的背景,并通过setStroke()方法来设置边框的颜色和宽度。
使用自定义的单选框时,只需要在XML布局文件中引用即可:
```xml
<com.example.CustomRadioButton
android:id="@+id/custom_radio_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Radio Button" />
```
注意,这里的包名需要替换成你自己的包名。