题
我为控件编写了一个自定义小部件,我们在整个应用程序中都广泛使用。小部件类来自 ImageButton
并以几种简单的方式扩展它。我定义了可以按使用的小部件应用的样式,但是我宁愿通过主题进行设置。在 R.styleable
我看到小部件样式属性 imageButtonStyle
和 textViewStyle
. 。有什么方法可以为我写的自定义小部件创建类似的东西?
解决方案
是的,有一种方法:
假设您有一个小部件的属性声明(在 attrs.xml
):
<declare-styleable name="CustomImageButton">
<attr name="customAttr" format="string"/>
</declare-styleable>
声明您将用于样式参考的属性(在 attrs.xml
):
<declare-styleable name="CustomTheme">
<attr name="customImageButtonStyle" format="reference"/>
</declare-styleable>
声明小部件的一组默认属性值(在 styles.xml
):
<style name="Widget.ImageButton.Custom" parent="android:style/Widget.ImageButton">
<item name="customAttr">some value</item>
</style>
声明自定义主题(在 themes.xml
):
<style name="Theme.Custom" parent="@android:style/Theme">
<item name="customImageButtonStyle">@style/Widget.ImageButton.Custom</item>
</style>
将此属性用作小部件构造函数中的第三个参数(在 CustomImageButton.java
):
public class CustomImageButton extends ImageButton {
private String customAttr;
public CustomImageButton( Context context ) {
this( context, null );
}
public CustomImageButton( Context context, AttributeSet attrs ) {
this( context, attrs, R.attr.customImageButtonStyle );
}
public CustomImageButton( Context context, AttributeSet attrs,
int defStyle ) {
super( context, attrs, defStyle );
final TypedArray array = context.obtainStyledAttributes( attrs,
R.styleable.CustomImageButton, defStyle,
R.style.Widget_ImageButton_Custom ); // see below
this.customAttr =
array.getString( R.styleable.CustomImageButton_customAttr, "" );
array.recycle();
}
}
现在您必须申请 Theme.Custom
进行所有使用的活动 CustomImageButton
(在AndroidManifest.xml中):
<activity android:name=".MyActivity" android:theme="@style/Theme.Custom"/>
就这样。现在 CustomImageButton
试图从 customImageButtonStyle
当前主题的属性。如果在主题或属性的值中找不到此类属性 @null
然后最后的论点 obtainStyledAttributes
将会被使用: Widget.ImageButton.Custom
在这种情况下。
您可以更改所有实例和所有文件的名称(除了 AndroidManifest.xml
)但是最好使用Android命名惯例。
其他提示
除了迈克尔的出色答案之外,另一个方面是主题中的自定义属性。假设您有许多自定义视图,所有自定义视图都参考自定义属性“ custom_background”。
<declare-styleable name="MyCustomStylables">
<attr name="custom_background" format="color"/>
</declare-styleable>
在主题中,您定义值是什么
<style name="MyColorfulTheme" parent="AppTheme">
<item name="custom_background">#ff0000</item>
</style>
或者
<style name="MyBoringTheme" parent="AppTheme">
<item name="custom_background">#ffffff</item>
</style>
您可以参考样式的属性
<style name="MyDefaultLabelStyle" parent="AppTheme">
<item name="android:background">?background_label</item>
</style>
注意问题标记,以及用于参考Android属性的参考
?android:attr/colorBackground
正如你们大多数人所注意到的那样,您可以 - 可能应该使用@Color引用,而不是硬编码颜色。
那为什么不这样做
<item name="android:background">@color/my_background_color</item>
您无法在运行时更改“ my_background_color”的定义,而您可以轻松切换主题。