इस कस्टम दृश्य MyView
होने में इस्तेमाल किया हो जाओ मैं कुछ कस्टम विशेषताओं को परिभाषित:drawable संदर्भ के लिए संसाधन आईडी स्टाइल विशेषता
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="normalColor" format="color"/>
<attr name="backgroundBase" format="integer"/>
</declare-styleable>
</resources>
और लेआउट एक्सएमएल में इस प्रकार के रूप में उन्हें आवंटित:
<com.example.test.MyView
android:id="@+id/view1"
android:text="@string/app_name"
. . .
app:backgroundBase="@drawable/logo1"
app:normalColor="@color/blue"/>
सबसे पहले मैंने सोचा कि मैं कस्टम विशेषता backgroundBase
का उपयोग कर प्राप्त कर सकता हूं:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank);
जो केवल तभी काम करता है जब विशेषता असाइन नहीं की जाती है और डिफ़ॉल्ट R.drawable.blank
वापस कर दिया जाता है।
जब app:backgroundBase
असाइन किया गया है एक अपवाद फेंक दिया जाता है "प्रकार पूर्णांक परिवर्तित नहीं किया जा सकता = 0xn" क्योंकि, भले ही कस्टम विशेषता प्रारूप पूर्णांक के रूप में यह घोषणा करता है, यह वास्तव में एक Drawable
का संदर्भ और इस प्रकार पुनः प्राप्त किया जाना चाहिए:
Drawable base = a.getDrawable(R.styleable.MyView_backgroundBase);
if(base == null) base = BitMapFactory.decodeResource(getResources(), R.drawable.blank);
और यह काम करता है।
अब मेरे सवाल:
मैं वास्तव में नहीं TypedArray से Drawable
प्राप्त करना चाहते हैं, मैं पूर्णांक आईडी app:backgroundBase
करने के लिए इसी (उदाहरण में ऊपर यह R.drawable.logo1
होगा) चाहते हैं। मैं इसे कैसे प्राप्त कर सकता हूँ?
कुछ स्पष्टीकरण है कि मुझे मदद की है जाएगा: 'R.drawable.blank' मामले में डिफ़ॉल्ट संसाधन का अनुरोध किया एक मौजूद नहीं है – HaydenKai