【问题标题】:Android: How to get an attribute from a super class of a custom viewAndroid:如何从自定义视图的超类中获取属性
【发布时间】:2015-01-15 08:35:06
【问题描述】:

我有一个自定义视图 A,它有一个 TextView。我做了一个方法,为 TextView 返回resourceID。如果没有定义文本,该方法将默认返回 -1。 我还有一个自定义视图B,它继承自视图A。我的自定义视图有文本“你好”。当我调用该方法来获取超类的属性时,我得到的是 -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>

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);
  }
}

到目前为止,我发现的另一个解决方案是执行以下操作。我也认为这有点 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>

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

【问题讨论】:

    标签: android inheritance android-custom-view declare-styleable android-attributes


    【解决方案1】:

    显然这是正确的做法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多