हाँ। लघु गाइड:
1. एक विशेषता XML बनाएँ
/res/values/attrs.xmlविशेषता के साथ अंदर एक नई XML फ़ाइल बनाएँ , और यह टाइप है
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="MyCustomElement">
<attr name="distanceExample" format="dimension"/>
</declare-styleable>
</resources>
मूल रूप से आपको <declare-styleable />अपने दृश्य के लिए एक सेट करना होगा जिसमें आपकी सभी कस्टम विशेषताएँ (यहाँ सिर्फ एक है)। मुझे संभावित प्रकारों की पूरी सूची कभी नहीं मिली, इसलिए आपको मेरे एक अनुमान के लिए स्रोत को देखने की जरूरत है। प्रकार जो मुझे पता है कि संदर्भ (दूसरे संसाधन के लिए) हैं, रंग, बूलियन, आयाम, फ्लोट, पूर्णांक और स्ट्रिंग । वे बहुत आत्म-व्याख्यात्मक हैं
2. अपने लेआउट में विशेषताओं का उपयोग करें
वह उसी तरह काम करता है जैसा आपने ऊपर किया था, एक अपवाद के साथ। आपके कस्टम विशेषता की आवश्यकता है कि यह XML नाम स्थान का अपना हो।
<com.example.yourpackage.MyCustomElement
xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
customNS:distanceExample="12dp"
/>
बहुत सीधा।
3. आपके द्वारा पास किए गए मूल्यों का उपयोग करें
मूल्यों को पार्स करने के लिए अपने कस्टम दृश्य के निर्माता को संशोधित करें।
public MyCustomElement(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0);
try {
distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f);
} finally {
ta.recycle();
}
// ...
}
distanceExampleइस उदाहरण में एक निजी सदस्य चर है। TypedArrayअन्य प्रकार के मूल्यों को पार्स करने के लिए बहुत सी अन्य चीजें मिलीं।
और बस। Viewइसे संशोधित करने के लिए अपने पार्स किए गए मान का उपयोग करें , उदाहरण के onDraw()अनुसार रूप बदलने के लिए इसका उपयोग करें ।