代码之家  ›  专栏  ›  技术社区  ›  Mark A. Donohoe

在属性的格式中(以颜色为例),“颜色”和“颜色|参考”之间有什么区别?

  •  3
  • Mark A. Donohoe  · 技术社区  · 7 年前

    TLDR版本

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

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

    <!-- 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 我可以根据需要得到定义的颜色。一切正常。我的控件主题恰当。

    然而,我想知道的是,我有时在ATTR中看到这一点。xml文件。。。

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

    一切都还顺利,让我挠头想你为什么要写 color|reference 颜色

    有人能解释吗?

    更好的是,有人能举一个例子来展示不同的行为吗 颜色 因为到目前为止,我还没有找到一个。

    1 回复  |  直到 7 年前
        1
  •  4
  •   VIN    3 年前

    颜色=任何颜色。十六进制(#ffffffff)或链接到颜色资源(@color/supa-awesome_color)。此处不允许使用@drawable/mega_图标

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