Android:如何从自定义视图的超类中获取属性

11

我有一个自定义视图A,其中包含一个TextView。我创建了一个方法,返回TextView的resourceID。如果没有定义文本,则该方法默认返回-1。 我还有一个自定义视图B,继承自视图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>

如何从自定义视图的超类中获取属性?我似乎找不到关于自定义视图继承如何工作的好例子。

1个回答

11

显然这是正确的方法:

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行处有一个示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接