我想知道为什么我的代码没有按照我认为的方式工作。我对原始的 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);
}
}
此更改是构造函数中的 R.style.MyRadioButton
。接下来,我在 styles.xml
中输入了以下行:
<!-- language: xml -->
<style name="MyRadioButton" parent="@android:style/Widget.CompoundButton.RadioButton" />
Widget.CompoundButton.RadioButton
是 style
,为 RadioButton
定义了 drawable
。
为了使用我自己的 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>
我认为我所做的是从默认 RadioButton
继承样式并在构造函数中使用该样式(与在原始 RadioButton
源代码中完成的方式相同)。问题是我的 RadioButton
没有显示任何 drawable
,只有文本,我想知道为什么?
它也不会对点击使用react,因为点击它不会取消选中“默认单选按钮”,尽管事实上两者都在 RadioGroup
中。
最佳答案
好吧,我终于在我的代码中发现了一个问题。
Android 文档说:
defStyleAttr
An attribute in the current theme that contains a reference to a style resource to apply to this view. If 0, no default style will be applied.
我做错的是传递 style
而不是 attr
(引用当前主题中的样式)。
所以这是解决方案:
public RadioButton(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.myRadioButtonStyle);
}
我没有修改 styles.xml
中的代码:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton" />
但我必须在 themes.xml
中创建自定义主题并将其应用于当前 Activity
:
<style name="MyTheme">
<item name="myRadioButtonStyle">@style/MyRadioButtonStyle</item>
</style>
在 attrs.xml
中:
<declare-styleable name="MyTheme">
<attr name="myRadioButtonStyle" format="reference" />
</declare-styleable>
我之前无法运行的代码是基于其他人的旧代码,其中 View
构造函数属性被命名为 defStyle
,这导致我犯了错误。 Android 开发人员通过将属性重命名为 defStyleAttr
来修复文档。这是一个记录它的问题:https://code.google.com/p/android/issues/detail?id=12683
上一篇文章清楚地说:
The documentation is incorrect. The third constructor must be an attribute, e.g.
R.attr.*
关于android - 在构造函数中使用自己的样式扩展 RadioButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20330642/