android - 如果您可以直接从 AttributeSet 中读取,为什么需要声明样式?

标签 android android-xml attr android-custom-view declare-styleable

我使用以下构造函数创建了一个自定义 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.xmldeclare-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/

相关文章:

Android - 使用 Thawte CA 的 SSL 证书连接到 Web 服务时出现 SSLPeerUnverifiedException

v7 支持库 ActionBar 的 Android Proguard 配置

android - ionic 平台添加 android 命令失败,退出代码为 ENOENT

android - 如何更改 XML 文件中的字体 android studio

jquery - jquery 中的 .id 和 .attr ('id' ) 有什么区别

javascript - jQuery attr 是否允许非标准?

android - 自定义属性不适用于 android 中的主题

android - 如何创建一个创建不连续边框的 xml 可绘制对象?

android - 约束布局指南不起作用

javascript - jQuery attr() 无法设置属性