我有一个A
具有TextView的自定义视图。我做了一个返回resourceID
TextView的方法。如果未定义任何文本,则默认情况下该方法将返回-1。我也有一个B
继承自view的自定义视图A
。我的自定义视图的文字为“ hello”。当我调用该方法以获取超类的属性时,我将返回-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>
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);
}
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);
}
}
TextView.java源代码中有一个示例。在1098行
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句