Android以编程方式从上下文主题获取资源(无需直接访问" R")

时间:2017-06-05 14:48:34

标签: android

我将我的代码分成两个项目,以便拥有某种SDK,其功能与我未来的所有项目相同。

所以我遇到了从另一个项目中检索一个项目的XML文件中的值的问题。例如,我必须在styles.xml中检索一种颜色,一种是自定义颜色(我在attrs.xml中定义,名为" iconColor")。这就是我的所作所为:

TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
int colorIdentifier = context.getResources().getIdentifier("iconColor", "attr", context.getPackageName());
if (theme.resolveAttribute(colorIdentifier, typedValue, true)) {
    return typedValue.data;
}
else {
    return 0;
}

它从一个项目到另一个项目工作正常。现在出于另一个目的,我想检索我的上下文主题的colorPrimary。我调整了我的代码以获得通用功能,现在就是这样的:

/**
 * Retrieves a resource from context's theme using the resource id
 *
 * @param resId the resource id, ie. android.R.attr.colorPrimary
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(int resId) {
    Integer result = null;

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    if (theme.resolveAttribute(resId, typedValue, true)) {
        result = typedValue.data;
    }

    return result;
}

/**
 * Retrieves a resource from context's theme using the resource name
 *
 * @param resName the resource name, ie. "colorPrimary"
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(@NonNull String resName) {
    int resId = context.getResources().getIdentifier(resName, "attr", context.getPackageName());
    return getResourceFromTheme(resId);
}

这样我就可以在理论上使用android.R检索自定义属性和本机属性。但是,如果它仍然在我的costom iconColor属性上工作,我无法检索colorPrimary,它会返回不正确的数据。甚至更奇怪,当我尝试使用一种方法或另一种方法时,我得到了不同的值,这意味着我得到了错误的代码:

enter image description here

1 个答案:

答案 0 :(得分:1)

好的,所以函数运行正常,但我犯了两个错误,xxxx是ColorRes,aaaa / bbbb是ColorInt,我用android.R.attr.colorPrimary而不是R.attr.colorPrimary调用我的函数。 / p>