Android:如何从自定义视图的超类中获取属性
我有一个自定义视图Android:如何从自定义视图的超类中获取属性,android,inheritance,android-custom-view,declare-styleable,android-attributes,Android,Inheritance,Android Custom View,Declare Styleable,Android Attributes,我有一个自定义视图a,它有一个文本视图。我为TextView创建了一个返回resourceID的方法。如果未定义文本,则默认情况下该方法将返回-1。 我还有一个自定义视图B,它继承自视图a。我的自定义视图包含文本“hello”。当我调用该方法来获取超类的属性时,我得到的是-1 在代码中还有一个示例,说明了如何检索值,但感觉有点粗糙 <attr name="mainText" format="reference" /> <declare-styleable name="A"&g
a
,它有一个文本视图。我为TextView创建了一个返回resourceID
的方法。如果未定义文本,则默认情况下该方法将返回-1。
我还有一个自定义视图B
,它继承自视图a
。我的自定义视图包含文本“hello”。当我调用该方法来获取超类的属性时,我得到的是-1
在代码中还有一个示例,说明了如何检索值,但感觉有点粗糙
<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>
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>
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); // 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>
如何从自定义视图的超类中获取属性?
我似乎找不到任何关于继承如何与自定义视图一起工作的好例子。显然这是正确的方法:
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);
}
}
第1098行的源代码中有一个示例