在属性的格式中(并使用Color作为示例),' color'之间的区别是什么?和'颜色|参考'?

时间:2017-08-03 13:42:37

标签: android android-theme android-styles android-attributes

TLDR版本

我明白为什么reference被用作设置默认主题时指向默认样式的属性的格式,但在定义颜色时使用reference|color与使用color的方式不同属性?您已经可以使用已经引用另一个资源的@color/xxx,因此引用是隐式的吗?如果没有,那么一个用户的用例是什么?

完整版

我一直在遵循使用以下推荐技术将应用程序的自定义小部件主题化的最佳实践。

在attrs.xml中

<!-- Attributes holding default styles -->
<attr name="myWidgetStyle"      format="reference" />
<attr name="myOtherWidgetStyle" format="reference" />

<!-- Custom attributes -->
<attr name="indicatorColor" format="color|reference" />

<!-- Assigning attributes to controls -->
<declare-styleable name="MyWidget">
    <item name="android:text" />
    <item name="indicatorColor" />
</declare-styleable>

<declare-styleable name="MyOtherWidget">
    <item name="android:text" />
    <item name="indicatorColor" />
</declare-styleable>

在styles.xml中

<style name="ThemeBase">

    <!-- Store default style in the style-reference attributes -->
    <item name="myWidgetStyle">@style/MyWidget</item>
    <item name="myOtherWidgetStyle">@style/MyOtherWidget</item>

    <!-- Reference primaryColor attribute when defining the value for this one -->
    <item name="indicatorColor">?primaryColor</item>
    <!-- alternate: <item name="indicatorColor">?attr/primaryColor</item> -->

</style>

<style name="ThemeA" parent="ThemeBase">
    <item name="primaryColor">@color/primaryColor_themeA</item>
</style>

<style name="ThemeB" parent="ThemeBase">
    <item name="primaryColor">@color/primaryColor_themeB</item>
</style>

最后,在我的小部件的构造函数中,我将R.attr.myWidgetStyleR.attr.myOtherWidgetStyle适当地传递给super以及context.obtainStyledAttributes,我可以根据需要获取定义的颜色。一切都按预期工作。我的控件以主题为主题。

然而,我想知道的是我有时会在attrs.xml文件中看到这个......

<attr name="indicatorColor" format="color" /> <-- Note no 'reference'

并且一切仍然有效,让我一直在思考为什么要写color|reference而不仅仅是color。我已尝试通过几个属性进行级联更改,以不同的顺序定义它们以及我能想到的任何其他结果,但它们都能正常工作。

所有人都有解释吗?

更好的是,有人可以发布一个示例,显示colorcolor|reference之间的不同行为,因为到目前为止,我还没有找到一个。

1 个答案:

答案 0 :(得分:0)

嗬!

属性格式仅供系统知道此属性的资源类型。

color =任何颜色。十六进制(#ffffffff)或指向颜色资源的链接(@ color / supa-awesome_color)。这里不允许@ drawable / mega_icon

reference =任何参考(@ color / supa_awesome_color,@ drawable / mega_icon,@ string / hi_there,...)

color | reference =是上述

的联合