【问题标题】:Custom attrs parameter used in styles.xmlstyles.xml 中使用的自定义 attrs 参数
【发布时间】:2010-11-24 10:03:29
【问题描述】:

我在 attrs.xml 中定义了一组自定义 Android 布局参数。现在我想在我的 styles.xml 文件中使用一些标签。

目前我收到此错误:

error: Error: No resource found that matches the given name: attr 'custom:tag'

我已尝试如下声明自定义 XML 命名空间:

<resources
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.my.project"
>

希望每个布局声明中使用的相同逻辑都可以在这里应用,但没有成功。

【问题讨论】:

  • 请张贴styles.xml中的代码
  • &lt;style name="my_style"&gt; &lt;item name="custom:tag"&gt;some_value&lt;/item&gt; &lt;/style&gt;

标签: android


【解决方案1】:

XML 命名空间机制用于命名标签和属性。当您定义这样的样式时:

<?xml version="1.0" encoding="utf-8"?>
<resources
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.my.project">

    <style name="my_style"> <item name="custom:tag">some_value</item> </style>

</resources>

您正在尝试将 XML 命名空间应用于属性 value,但这是行不通的。在这种情况下,您应该直接指定包名称,如下所示:

    <style name="my_style"> <item name="com.my.project:tag">some_value</item> </style>

现在 Android 将能够解析属性的定义位置。

【讨论】:

  • 好的,如果不同命名空间中有一些同名的标签怎么办?
  • 这是一个很好的问题。经过进一步调查,我意识到我之前的答案不完整,请查看更新后的答案。
  • 据我了解,应该在布局 xml 中引用命名空间?仅在这种情况下对我有用
  • 如果您在 layout.xml 中使用 style 属性来引用包含带有 custom:tag 的项目的样式,则不需要在 layout.xml 中声明 xmlns:custom。如果您使用 layout.xml 中 custom 命名空间中的标签或属性,则只需在 layout.xml 中声明 xmlns:custom。 (希望我正确理解了你的问题,如果不是这样,请原谅我。)
  • 在布局文件的根标签中添加xml命名空间引用。
【解决方案2】:

接受的解决方案对我不起作用,但它对情况有所了解。

自定义属性已解析并可在全局项目的包名中引用,例如“com.ltst.project”。即使您有多个模块(具有相同的基本包名称),资源也会在项目的包名称中解析。

所以对我来说,省略样式中自定义属性的任何前缀就足够了。

自定义属性:

<declare-styleable name="SampleView">
    <attr name="sample_color" format="reference" />
</declare-styleable>

风格:

<style name="SampleStyle">
    <item name="sample_color">@color/sample_color</item>
</style>

【讨论】:

    【解决方案3】:

    你可以使用链接

    xmlns: app = "http://schemas.android.com/apk/res-auto

    并将每个标签的前缀定义为 app

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 2019-02-25
      相关资源
      最近更新 更多