I have a custom view A that has a TextView. I created a method that returns resourceID for a TextView. If no text is specified, the method will return -1 by default. I also have a custom view B that inherits from view A My custom view has the text hello. When I call the method to get the attribute of the super class, I get -1 back.
There is also an example in the code of how I can get the value, but it feels like a hack.
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>
Class A
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); }
Class B
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);
Another solution that I have found so far is the following. I also think this is hacky.
<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>
How to get attribute from superclass of custom view? I cannot find good examples of how inheritance works with custom views.
android inheritance android-custom-view
Wirling
source share