来自Android Studio中其他模块的参考资源

时间:2015-05-13 19:49:43

标签: android android-studio android-resources

我有一个主app模块以及一些库模块。

我的Library模块如何从Main App模块引用资源。

例如: 我的基本应用程序有一个colors.xml,它有一个名为“AppPrimary”的颜色项,它是蓝色的。

在我的库中,我希望xml布局中的视图能够引用@ color / AppPrimary颜色,但这不起作用。

我怎样才能做到这一点?

编辑:我应该指定这不是专门的appCompat资源。在我的主模块中只是通用字符串/颜色/样式/。如何在我的库模块colors.xml / strings.xml中的同一项目中引用它们?

2 个答案:

答案 0 :(得分:8)

在xml布局参考?attr/colorPrimary中的库模块中,而不是@color/AppPrimary

这会引用应用主题中的调色板属性。即;

<item name="colorPrimary">@color/AppPrimary</item>

您还可以参考其他调色板属性,如:

<item name="colorPrimaryDark">...</item> -> ?attr/colorPrimaryDark
<item name="colorAccent">...</item> -> ?attr/colorAccent

等等。

Please refer to this documentation

<强> CAVEAT
这些示例引用了主题中的AppCompat实现。即没有android:名称空间前缀。

- 编辑 -

简短的回答是,您无法从引用库colors.xml文件的主模块中“获取”定义的颜色。

但是,您可以在主题中利用自定义属性来实现相同的效果。

这可以通过在库模块的attrs.xml文件中声明一个通用样式来实现,像这样:

<declare-styleable name="BaseTheme">
    <attr name="someColor" format="reference|color" />
</declare-styleable>

注意:styleable的名称与此实现无关,因此请随意为其命名。

然后在“style.xml”或“theme.xml”文件中的主模块主题定义中,您需要将此属性设置为您要共享的颜色,如下所示:

<style name="Theme.Example" parent="Theme.AppCompat.Light.NoActionBar">

    <!-- Color Palette -->
    <item name="colorPrimary">...</item>
    <item name="colorPrimaryDark">...</item>
    <item name="colorAccent">...</item>

    <!-- Here we define our custom attributes -->
    <item name="someColor">@color/dark_blue</item>

</style>

定义完成后,您可以在库模块XML代码中引用该属性。 e.g;

<TextView
    ...
    android:textColor="?attr/someColor"
    />

答案 1 :(得分:0)

以下是以编程方式在库模块中获取颜色属性的方法。

@ColorInt
public static int getAttributeColor(Context context, @AttrRes int colorAttribute)
{
    int[] attrs = {colorAttribute};
    TypedArray ta = context.obtainStyledAttributes(attrs);
    /*Get the color resourceID that we want (the first index, and only item, in the
    attrs array). Use ContextCompat to get the color according to the theme.
    */
    @ColorInt int color = ContextCompat.getColor(context,
                                                 ta.getResourceId(0, -1));
    // ALWAYS call recycle() on the TypedArray when you’re done.
    ta.recycle();
    return color;
}

实施例

//Get the main applications ‘colorAccent' from the app’s color palette.
int appAccentColor = Utility.getMarketAttributeColor(context, R.attr.colorAccent);

//Get the color attribute your module made for the client app to define.
int moduleAttrColor = Utility.getMarketAttributeColor(context, R.attr.moduleColorAttr);

注意:此基本属性检索过程适用于大多数属性类型。