Sì, c'è un modo:
Supponi di avere una dichiarazione di attributi per il tuo widget (in attrs.xml
):
<declare-styleable name="CustomImageButton">
<attr name="customAttr" format="string"/>
</declare-styleable>
Dichiara un attributo che utilizzerai per un riferimento allo stile (in attrs.xml
):
<declare-styleable name="CustomTheme">
<attr name="customImageButtonStyle" format="reference"/>
</declare-styleable>
Dichiarare un insieme di valori di attributi predefiniti per il widget (in styles.xml
):
<style name="Widget.ImageButton.Custom" parent="android:style/Widget.ImageButton">
<item name="customAttr">some value</item>
</style>
Dichiara un tema personalizzato (in themes.xml
):
<style name="Theme.Custom" parent="@android:style/Theme">
<item name="customImageButtonStyle">@style/Widget.ImageButton.Custom</item>
</style>
Usa questo attributo come terzo argomento nel costruttore del tuo widget (in 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 );
this.customAttr =
array.getString( R.styleable.CustomImageButton_customAttr, "" );
array.recycle();
}
}
Ora devi applicare Theme.Custom
a tutte le attività che utilizzano CustomImageButton
(in AndroidManifest.xml):
<activity android:name=".MyActivity" android:theme="@style/Theme.Custom"/>
È tutto. Ora CustomImageButton
prova a caricare i valori degli attributi predefiniti dall'attributo customImageButtonStyle
del tema corrente. Se non viene trovato alcun attributo di questo tipo nel tema o nel valore dell'attributo, verrà utilizzato @null
l'argomento finale di obtainStyledAttributes
: Widget.ImageButton.Custom
in questo caso.
Puoi cambiare i nomi di tutte le istanze e di tutti i file (eccetto AndroidManifest.xml
) ma sarebbe meglio usare la convenzione di denominazione Android.