我正在尝试通过其构造函数设置自定义 View 的样式。它没有达到预期的效果。
QueueButton.java
public class QueueButton extends ImageButton {
public QueueButton(Context context) {
super(context);
}
public QueueButton(Context context, AttributeSet attrs) {
super(context, attrs, R.style.queuebutton);
}
public QueueButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, R.style.queuebutton);
}
}
(布局中)
<QueueButton
android:id="@+id/queueBtn"
style="@style/queuebutton"
android:layout_width="50dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:focusable="false"
android:src="@drawable/remove_queue_icon" />
在下面的屏幕截图中,存在三种不同的结果。
- 左:所描述的类的结果,但没有 XML 中声明的样式。
- 中:相同的 XML,但在双参数构造函数中使用
super(context, attrs)
。 - 右:在 XML 中声明样式的结果。这就是所需的外观。
显然,这是错误的做法。我无法找到相关信息来说明原因以及如何实现适当的结果。
最佳答案
我相信您需要直接传递属性而不是样式。
向您的 attrs.xml 文件添加一个属性(如果您还没有属性,则在 Values 文件夹中创建一个属性)。 然后为您的应用程序创建一个主题,并将新属性链接到该主题中所需的样式(或者,如果您已经在使用现有主题,则只需将其添加到现有主题中)。 最后,在自定义 View 构造函数中将属性传递给 super 构造函数。 Android 将在上下文的主题中查找该属性(根据文档),并且应该使用它。 但请注意,如果在 XMl 中指定了样式,它将覆盖您在构造函数中使用的样式,因为它具有优先权。
事情最终应该是这样的:
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="queueButtonStyle" format="reference" />
</resources>
样式.xml:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
<item name="queueButtonStyle">@style/queuebutton</item>
</style>
<style name="queuebutton">
...content...
</style>
以及自定义 View 类构造函数:
public class QueueButton extends ImageButton {
public QueueButton(Context context) {
super(context);
}
public QueueButton(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.queueButtonStyle);
}
public QueueButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, R.attr.queueButtonStyle);
}
}
关于android - 自定义 View 构造函数中的重写样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812156/