在属性的格式中(以 Color 为例),'color' 和"color|reference"之间有什么区别?



TLDR version

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

完整版

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

在吸引.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>

在风格上.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传递给对supercontext.obtainStyledAttributes的调用,我可以根据需要获得定义的颜色。 一切都按预期工作。我的控件主题适当。

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

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

一切仍然有效,让我摸不着头脑,为什么你会写color|reference而不仅仅是color. 我尝试通过多个属性级联更改,以不同的顺序定义它们以及我能想到的任何其他方法来获得不同的结果,但它们都有效。

那么有人有解释吗?

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

属性格式仅用于让系统知道此属性可以是哪种类型的资源。

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

引用 = 任何引用(@color/supa_awesome_color、@drawable/mega_icon、@string/hi_there等(

颜色|参考 = 是上述的并集

最新更新