我使用以下构造函数创建了一个自定义 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 会告诉您在 res/values/attrs.xml
的 declare-styleable
中定义自定义 View 的 XML 属性(已讨论 here )并应用通过调用 context.getTheme().obtainStyledAttributes()
(已讨论 here )来获取它们?
最佳答案
我傻了。我发布的第二个链接确实解释了原因:
When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view's constructor as an AttributeSet. Although it's possible to read values from the AttributeSet directly, doing so has some disadvantages:
- Resource references within attribute values are not resolved
- Styles are not applied
Instead, pass the AttributeSet to obtainStyledAttributes(). This method passes back a TypedArray array of values that have already been dereferenced and styled.
关于android - 如果您可以直接从 AttributeSet 中读取,为什么需要声明样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142052/