简要版
我理解当设置默认主题时,为什么使用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.myWidgetStyle
和R.attr.myOtherWidgetStyle
传递给super
的调用以及context.obtainStyledAttributes
,然后可以按需获取定义的颜色。一切都按预期工作。我的控件得到了适当的主题。
然而,我想知道的是,有时在attrs.xml文件中会看到这个...
<attr name="indicatorColor" format="color" /> <-- Note no 'reference'
而且所有的东西都还能正常工作,这让我感到困惑,为什么你要写“color|reference”而不是只写“color”。我尝试了通过多个属性级联更改、以不同的顺序定义它们以及其他我能想到的任何方法来获得不同的结果,但它们都能正常工作。
那么有人能解释一下吗?
更好的是,有人能够提供一个示例,展示“color”和“color|reference”之间不同的行为吗?因为截至目前,我还没有找到这样的例子。
<attr name="background" format="reference|color" />
- 它被注释为:*<!-- 用作背景的可绘制对象。这可以是对完整可绘制资源(例如PNG图像,9-patch,XML状态列表描述等)的引用,也可以是纯色,例如“#ff000000”(黑色)。-->* - pskinkformat
确实有问题,请参见我的评论。 - pskink