项目迁移到androidx,用低版本的手机(android4.4)测试,发现xml中的用"android:button=null"不起作用了,所有的RadioButton和Checkbox自带的按钮都显示出来了。
查看源码,发现第二个构造参数多了个默认属性
com.android.internal.R.attr.radioButtonStyle
如:RadioButton和AppCompatRadioButton源码(CheckBox和AppCompatCheckBox一样)
RadioButton:
public class RadioButton extends CompoundButton {
public RadioButton(Context context) {
this(context, null);
}
public RadioButton(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.radioButtonStyle);
}
public RadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public RadioButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
AppCompatRadioButton:
public class AppCompatRadioButton extends RadioButton implements TintableCompoundButton,
TintableBackgroundView {
private final AppCompatCompoundButtonHelper mCompoundButtonHelper;
private final AppCompatBackgroundHelper mBackgroundTintHelper;
private final AppCompatTextHelper mTextHelper;
public AppCompatRadioButton(Context context) {
this(context, null);
}
public AppCompatRadioButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.radioButtonStyle);
}
public AppCompatRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(TintContextWrapper.wrap(context), attrs, defStyleAttr);
mCompoundButtonHelper = new AppCompatCompoundButtonHelper(this);
mCompoundButtonHelper.loadFromAttributes(attrs, defStyleAttr);
mBackgroundTintHelper = new AppCompatBackgroundHelper(this);
mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr);
mTextHelper = new AppCompatTextHelper(this);
mTextHelper.loadFromAttributes(attrs, defStyleAttr);
}
解决方法一:重新第二个构造方法,把defStyleAttr默认为0(CheckBox原理一样)
public class MyRadioButton extends AppCompatRadioButton {
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs,0);
}
}
然后布局文件使用自定义的RadioButton
解决方法二:设置Style,可以在Application统一设置,项目中所有的就统一更改了(当然也可以每个单独设置)
<!-- Base application theme. -->
<style name="AppTheme_white" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/white</item>
<item name="colorPrimaryDark">@color/white</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="radioButtonStyle">@style/RadioButton_no</item>
<item name="checkboxStyle">@style/CheckBox_no</item>
</style>
<style name="RadioButton_no" parent="Widget.AppCompat.CompoundButton.RadioButton">
<item name="buttonCompat">@null</item>
<item name="android:background">@null</item>
</style>
<style name="CheckBox_no" parent="Widget.AppCompat.CompoundButton.CheckBox">
<item name="buttonCompat">@null</item>
<item name="android:background">@null</item>
</style>
完美解决!
![](https://i-blog.csdnimg.cn/blog_migrate/f96d1f1b1225905f9818344f924e20ed.jpeg)