Да, есть один способ:
Предположим, у вас есть объявление атрибутов для вашего виджета (в 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.