7
我有一个具有TextView的自定义视图A
。我做了一个方法,返回TextView的resourceID
。如果未定义文本,则该方法默认返回-1。 我也有从视图A
继承的自定义视图B
。我的自定义视图有文字'hello'。当我调用方法来获取超类的属性时,我会返回-1。Android:如何从自定义视图的超类中获取属性
在代码中还有一个例子,我如何能够检索的价值,但它感觉有点哈克。
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);
}
}
另一种解决方案我得到f到目前为止,要做到以下几点。我也认为这有点哈克。
<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>
如何从自定义视图的超类中获取属性? 我似乎无法找到有关如何继承与自定义视图工作的任何好例子。