2

我使用以下构造函数创建了一个自定义 View 子类:

public MyCustomView(Context context, AttributeSet attrs)
{
    super(context, attrs);

    // get custom "thingy" attribute specified in XML
    int thingy = attrs.getAttributeIntValue(MY_NAMESPACE, "thingy", 0);

    //rest of constructor
    ...
}

可以看出,它从其 XML 属性中获取了一个自定义的“thingy”属性。这工作得很好,到目前为止我没有遇到任何问题。那么,为什么 Google 会告诉您在declare-styleablein res/values/attrs.xml(在此处讨论context.getTheme().obtainStyledAttributes()中定义自定义 View 的 XML 属性并通过调用(在此处讨论)来应用它们?

4

1 回答 1

3

我很笨。我发布的第二个链接确实解释了原因:

当从 XML 布局创建视图时,XML 标记中的所有属性都从资源包中读取,并作为 AttributeSet 传递到视图的构造函数中。虽然可以直接从 AttributeSet 中读取值,但这样做有一些缺点:

  • 属性值中的资源引用未解析
  • 未应用样式

相反,将 AttributeSet 传递给 gainStyledAttributes()。此方法传回一个 TypedArray 数组,该数组包含已取消引用和样式化的值。

于 2013-01-03T16:00:35.767 回答