10

ATextView を持つカスタム ビューがあります。resourceIDTextViewの を返すメソッドを作成しました。テキストが定義されていない場合、メソッドはデフォルトで -1 を返します。Bviewから継承するカスタム ビューもありますA。私のカスタム ビューには、「こんにちは」というテキストがあります。スーパー クラスの属性を取得するメソッドを呼び出すと、代わりに -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>

カスタムビューのスーパークラスから属性を取得するには? 継承がカスタム ビューでどのように機能するかについての良い例が見つからないようです。

4

1 に答える 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行目

于 2015-01-15T09:08:03.397 に答える