是否可以添加自定义属性到风格在Android资源?自定义、属性、风格、资源

2023-09-04 12:30:23 作者:如花似玉

我是一个使用视图流组件到我的项目,它允许开发覆盖一些属性,这样的:

I'm a using a view flow component into my project, which allows the dev to override some attributes, like that :

<org.taptwo.android.widget.TitleFlowIndicator
    ...
    app:footerTriangleHeight="0dip"
    ... />

我重用组件分成若干布局,我想放的属性变成一个风格。 但是,当我这样做,解析器说错误:未发现的资源匹配给定名称:ATTR应用程序:footerTriangleHeight,即使我添加了命名空间中的样式文件。

I am reusing this component into several layouts, and I would like to put the properties into a style. But when I'm doing this, the parser says Error: No resource found that matches the given name: attr 'app:footerTriangleHeight', even if I add the namespace in the styles file.

有没有办法做到这一点在Android的?

Is there a way to do that in android ?

感谢。

推荐答案

Android应用程序

如果你不使用的Andr​​oid库,那么这里就是你可以做什么:

If you are not using Android Libraries, then here is what you can do:

定义自定义设置样式属性(我猜你已经这样做了)。 不得使用风情项目的命名空间preFIX(命名空间默认为当前应用程序的命名空间)。

例如:

在 attrs.xml 的:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="testAttr" format="string"/>        
</resources>

在 styles.xml 的:

<?xml version="1.0" encoding="utf-8"?>
<resources>        
    <style name="TestStyle" >
      <item name="testAttr">asdf</item>
    </style>        
</resources>

的Andr​​oid库

如果自定义属性来自于Android的图书​​馆,你仍然可以使用描述的方法。它理论上应该工作,由于Android库的命名空间是相同的应用程序(由 AAPT 工具的角度构建过程中)。但我还没有测试此我自己。

If custom attribute comes from Android Library, you can still use described approach. It theoretically should work, because Android Library's namespace is the same as application's (from aapt tool perspective during the build). But I haven't test this myself.

如果你指定的命名空间,它会显示错误。据我所知,样式不支持XML命名空间。因此,这会失败:

If you're specifying namespace, it will show error. As far as I know, styles do not support xml namespaces. So this will fail:

在 styles.xml 的:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:app="http://schemas.android.com/apk/res/app.package.name">        
    <style name="TestStyle" >
      <item name="app:testAttr">asdf</item>
    </style>        
</resources>

分析器会自动默认为当前应用程序的 AndroidManifest 命名空间,虽然你不能明确指定该命名空间。

Parser automatically defaults to current app's AndroidManifest namespace, though you can not specify this namespace explicitly.