हां, इसका एक तरीका है:
मान लीजिए कि आपके पास अपने विजेट (इन 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 );
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 नामकरण सम्मेलन का उपयोग करना बेहतर होगा।