项目迁移到Androidx,在安卓5.0以下手机运行时,RadioButton设置button为null不起作用

项目迁移到androidx,用低版本的手机(android4.4)测试,发现xml中的用"android:button=null"不起作用了,所有的RadioButton和Checkbox自带的按钮都显示出来了。

项目迁移到Androidx,在安卓5.0以下手机运行时,RadioButton设置button为null不起作用_第1张图片

查看源码,发现第二个构造参数多了个默认属性

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统一设置,项目中所有的就统一更改了(当然也可以每个单独设置)

 
    
    
    

完美解决!

项目迁移到Androidx,在安卓5.0以下手机运行时,RadioButton设置button为null不起作用_第2张图片 解决之后

 

你可能感兴趣的:(安卓开发,AndroidX,CheckBox)