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

Wir*_*ing 8 inheritance android android-custom-view declare-styleable android-attributes

我有一个A具有TextView 的自定义视图.我做了一个返回resourceIDTextView的方法.如果未定义文本,则默认情况下该方法将返回-1.我还有一个B从视图继承的自定义视图A.我的自定义视图的文本为"hello".当我调用方法来获取超类的属性时,我得到了-1.

在代码中还有一个例子,我可以如何检索值,但感觉有点hacky.

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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我发现的另一个解决方案是执行以下操作.我也觉得这有点像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>
Run Code Online (Sandbox Code Playgroud)

如何从自定义视图的超类中获取属性?我似乎无法找到有关继承如何与自定义视图一起使用的任何好例子.

Wir*_*ing 10

显然这是正确的方法:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

TextView.java的源代码中有一个示例.在第1098行