Android 在构造函数中使用自己的样式扩展RadioButton
我想知道为什么我的代码没有按我认为应该的方式工作。我扩展了原来的Android 在构造函数中使用自己的样式扩展RadioButton,android,radio-button,android-drawable,android-styles,Android,Radio Button,Android Drawable,Android Styles,我想知道为什么我的代码没有按我认为应该的方式工作。我扩展了原来的RadioButton小部件,只做了一点改动。代码如下: <!-- language: java --> public class RadioButton extends android.widget.RadioButton { public RadioButton(Context context) { super(context); } public RadioButton(
RadioButton
小部件,只做了一点改动。代码如下:
<!-- language: java -->
public class RadioButton extends android.widget.RadioButton {
public RadioButton(Context context) {
super(context);
}
public RadioButton(Context context, AttributeSet attrs) {
super(context, attrs, R.style.MyRadioButton);
}
public RadioButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
Widget.CompoundButton.RadioButton
是样式
,它为RadioButton
定义了可绘制的。
要使用我自己的单选按钮
我做了一个布局:
我认为我所做的是从默认的RadioButton
继承了样式,并在构造函数中使用该样式(与在原始RadioButton
源代码中使用的方式相同)。问题是我的单选按钮
没有显示任何可绘制的
,只是文本,我想知道为什么
它也不会在点击时做出反应,因为点击它不会取消选中“默认单选按钮”,尽管这两个按钮都在RadioGroup
好的,我终于在代码中发现了一个问题
Android文档说:
defStyleAttr
当前主题中的一个属性,其中包含对要应用于此视图的样式资源的引用。如果为0,则不会应用默认样式
我犯的错误是传递了style
,而不是attr
(引用当前主题中的样式)。
因此,解决方案如下:
我在styles.xml中保留了未触及的代码:
在attrs.xml
中:
最后一篇文章明确指出:
文件不正确。第三个构造函数必须是属性,例如R.attr.*
<!-- language: xml -->
<style name="MyRadioButton" parent="@android:style/Widget.CompoundButton.RadioButton" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Default radio button" />
<com.example.test.RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="My radio button" />
</RadioGroup>
</LinearLayout>
public RadioButton(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.myRadioButtonStyle);
}
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton" />
<style name="MyTheme">
<item name="myRadioButtonStyle">@style/MyRadioButtonStyle</item>
</style>
<declare-styleable name="MyTheme">
<attr name="myRadioButtonStyle" format="reference" />
</declare-styleable>