如果@ {android.R.attr.textColorPrimary}解析为Java中的android.R.attr.textColorPrimary的值,则需要做的就是将其解析为颜色.
有一个设置进入这个.
ContextUtils.java
以下方法将上下文的主题和可选样式的提供的attr解析为颜色.如果出现错误,则返回到后备颜色.
@ColorInt
public static int resolveColor(final Context context, @StyleRes final int style, @AttrRes final int attr, @ColorInt final int fallback) {
final TypedArray ta = obtainTypedArray(context, style, attr);
try {
return ta.getColor(0, fallback);
} finally {
ta.recycle()
}
}
@ColorInt
public static int resolveColor(final Context context, @AttrRes final int attr, @ColorInt final int fallback) {
return resolveColor(context, 0, attr, fallback);
}
有效实现上述目标的实用方法.
private static TypedArray obtainTypedArray(final Context context, @StyleRes final int style, @AttrRes final int attr): TypedArray {
final int[] tempArray = getTempArray();
tempArray[0] = attr;
return context.obtainStyledAttributes(style, tempArray);
}
private static final ThreadLocal TEMP_ARRAY = new ThreadLocal<>();
private static final int[] getTempArray() {
int[] tempArray = TEMP_ARRAY.get();
if (tempArray == null) {
tempArray = int[1];
TEMP_ARRAY.set(tempArray);
}
return tempArray;
}
更复杂的代码在my android-commons library(这部分写在科特林,拿你需要的).
Bindings.java
以下是如何使用它:
@BindingAdapter({"bind:htmlTextColor"})
public static void setHtml(final WebView webView, @AttrRes final int textColorAttr) {
final Context context = webView.getContext();
final int textColor = ContextUtils.resolveColor(context, textColorAttr, Color.BLACK);
// binding logic
}