【问题标题】:error: Error: No resource found that matches the given name (for attribute reference)错误:错误:未找到与给定名称匹配的资源(用于属性参考)
【发布时间】:2018-11-17 21:35:24
【问题描述】:

我的 account_particle.xml 布局中有这一行

            android:padding="?attrs/disc_padding"

这个 attrs.xml:

<resources>
  <declare-styleable name="AccountParticle">
    <attr name="apStyle" format="enum">
      <enum name="header" value="0"/>
      <enum name="list_item" value="1"/>
    </attr>

    <attr name="text_margin_start" format="reference"/>
    <attr name="text_margin_end" format="reference"/>
    <attr name="text_margin_right" format="reference"/>
    <attr name="text_margin_left" format="reference"/>
    <attr name="disc_padding" format="reference"/>
    <attr name="disc_imageViewSize" format="reference"/>


  </declare-styleable>
</resources>

还有这个styles.xml:

<style name="Theme.ap.header" parent="Theme.AppCompat">
    <item name="disc_padding">@dimen/account_menu_header_signed_in_avatar_margin_start</item>
  </style>

  <style name="Theme.ap.list_item" parent="Theme.AppCompat">
    <item name="disc_padding">@dimen/account_menu_account_list_item_avatar_margin_start</item>



      </style>

为什么会出现这个编译错误?

 error: Error: No resource found that matches the given name (at 'padding' with value '?attrs/disc_padding').

帐户粒子

【问题讨论】:

  • 错字。 attr 上没有 s。也就是说,应该是android:padding="?attr/disc_padding"
  • 但它在 attrs.xml 上
  • 这只是一个文件名。实际资源将在R.attr 类中创建。实际上,您将res/values*/ 文件夹下的任何文件命名为什么,或者将任何资源放在哪个文件中都没有关系;它们都根据它们的类型进行处理,例如&lt;attr&gt;
  • 你能把它写成答案吗?
  • 当然,我可以把它放在答案中。由于您打算将其设为attrs,因此这不仅仅是一个简单的错字。给我一分钟。谢谢!

标签: android android-layout styles custom-attributes


【解决方案1】:

在布局属性中引用主题属性值的正确语法是:

prefix:attribute="?attr/themeAttribute"

attr 而不是attrs

虽然您可能在名为attrs.xml 的文件中定义了该属性,但文件名实际上是无关紧要的。在构建资源时,无论文件名如何,都会处理res/values*/ 文件夹下的每个文件。

这实际上意味着您可以随意命名您的文件,并且您可以将任何资源放入您想要的任何文件中。它们都将根据它们的类型进行处理,如&lt;attr&gt;&lt;color&gt;&lt;string&gt;等。

【讨论】:

    【解决方案2】:

    问题与属性用法有关,它应该是 ?attr/ 而不是 ?attrs/


    但是您的attrs.xml 文件中还有另一个问题。问题是您在 declare-styleable 中声明了以下引用:

    <attr name="text_margin_start" format="reference"/>
    <attr name="text_margin_end" format="reference"/>
    <attr name="text_margin_right" format="reference"/>
    <attr name="text_margin_left" format="reference"/>
    <attr name="disc_padding" format="reference"/>
    <attr name="disc_imageViewSize" format="reference"/>
    

    这个引用应该移到declare-styleable之外

    为什么

    declare-styleable 用于定义一组attrs,将在自定义视图的上下文中使用。在您的情况下,disc_paddingAccountParticle 的上下文之外使用。

    文档参考:https://developer.android.com/training/custom-views/create-view#customattr

    【讨论】:

    • 谢谢,但我的意思是布局是 account_particle.xml
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多