是的,有一种方法:
假设您有一个小部件的属性声明(在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 命名约定。