7

मेरे पास एक कस्टम व्यू A है जिसमें टेक्स्ट व्यू है। मैंने एक विधि बनाई है जो TextView के लिए resourceID देता है। यदि कोई पाठ परिभाषित नहीं किया गया है तो विधि डिफ़ॉल्ट रूप से -1 वापस आ जाएगी। मेरे पास कस्टम दृश्य B भी है जो A देखने से प्राप्त होता है। मेरे कस्टम व्यू में 'हैलो' टेक्स्ट है। जब मैं सुपर क्लास की विशेषता प्राप्त करने के लिए विधि को कॉल करता हूं तो मुझे इसके बजाय -1 वापस मिलता है।एंड्रॉइड: कस्टम दृश्य के सुपर क्लास से एक विशेषता कैसे प्राप्त करें

कोड में यह भी एक उदाहरण है कि मैं मूल्य कैसे प्राप्त कर सकता हूं लेकिन यह हैकी की तरह लगता है।

attrs.xml

<declare-styleable name="A"> 
    <attr name="mainText" format="reference" /> 
</declare-styleable> 

<declare-styleable name="B" parent="A"> 
    <attr name="subText" format="reference" /> 
</declare-styleable> 

क्लास ए

protected static final int UNDEFINED = -1; 

protected void init(Context context, AttributeSet attrs, int defStyle) 
{ 
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.A, defStyle, 0); 

    int mainTextId = getMainTextId(a); 

    a.recycle(); 

    if (mainTextId != UNDEFINED) 
    { 
     setMainText(mainTextId); 
    } 
} 

protected int getMainTextId(TypedArray a) 
{ 
    return a.getResourceId(R.styleable.A_mainText, UNDEFINED); 
} 

कक्षा बी

protected void init(Context context, AttributeSet attrs, int defStyle) 
{ 
    super.init(context, attrs, defStyle); 

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.B, defStyle, 0); 

    int mainTextId = getMainTextId(a); // this returns -1 (UNDEFINED) 

    //this will return the value but feels kind of hacky 
    //TypedArray b = context.obtainStyledAttributes(attrs, R.styleable.A, defStyle, 0); 
    //int mainTextId = getMainTextId(b); 

    int subTextId = getSubTextId(a); 

    a.recycle(); 

    if (subTextId != UNDEFINED) 
    { 
    setSubText(subTextId); 
    } 
} 

एक अन्य समाधान मैं च है अब तक निम्नलिखित करना है। मुझे यह भी लगता है कि यह हैकी है।

<attr name="mainText" format="reference" /> 

<declare-styleable name="A"> 
    <attr name="mainText" /> 
</declare-styleable> 

<declare-styleable name="B" parent="A"> 
    <attr name="mainText" /> 
    <attr name="subText" format="reference" /> 
</declare-styleable> 

कस्टम दृश्य के सुपर क्लास से एक विशेषता कैसे प्राप्त करें? मुझे कस्टम विचारों के साथ विरासत कैसे काम करता है इस पर कोई अच्छा उदाहरण नहीं दिख रहा है।

उत्तर

8

जाहिर है इस यह करने के लिए सही तरीका है:

protected void init(Context context, AttributeSet attrs, int defStyle) { 
    super.init(context, attrs, defStyle); 

    TypedArray b = context.obtainStyledAttributes(attrs, R.styleable.B, defStyle, 0); 
    int subTextId = getSubTextId(b); 
    b.recycle(); 

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.A, defStyle, 0); 
    int mainTextId = getMainTextId(a); 
    a.recycle(); 

    if (subTextId != UNDEFINED) { 
     setSubText(subTextId); 
    } 
} 

लाइन पर TextView.java. के स्रोत पर एक उदाहरण है 1098

संबंधित मुद्दे