在布局绑定中使用属性资源(?attr /)?

hid*_*dro 25 android android-layout android-databinding

数据Android中结合目前似乎支持以下参考资源(根据数据绑定引导): ,@array,@color,,@int ...,这将给参考值作为静态参数方法.@dimen@string@BindingAdapter

例如:

布局/ web_view.xml

<WebView
    app:htmlTextColor="@{@color/colorText}"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Run Code Online (Sandbox Code Playgroud)

Bindings.java

@BindingAdapter({"bind:htmlTextColor"})
public static void setHtml(WebView webView, int textColor) {
    // binding logic
}
Run Code Online (Sandbox Code Playgroud)

但随着主题和风格,它更多的时候,我用一个属性的资源,例如?android:attr/textColorPrimary@color参考.对于这种情况,绑定"@{}"语法将如何?目前这是我如何使它工作,但也许有更好的方法?

布局/ web_view.xml

<WebView
    app:htmlTextColor="@{android.R.attr.textColorPrimary}"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Run Code Online (Sandbox Code Playgroud)

Bindings.java

@BindingAdapter({"bind:htmlTextColor"})
public static void setHtml(WebView webView, int textColorAttr) {
    // binding logic
}
Run Code Online (Sandbox Code Playgroud)

Eug*_*nec 2

如果@{android.R.attr.textColorPrimary}解析为 Java 中的值android.R.attr.textColorPrimary,您所需要做的就是将其解析为颜色。

这里面有一些设置。

ContextUtils.java

以下方法解析提供attrcontext主题和可选style颜色。fallback如果出现错误,则返回颜色。

@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);
}
Run Code Online (Sandbox Code Playgroud)

有助于有效实现上述目标的实用方法。

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<int[]> 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;
}
Run Code Online (Sandbox Code Playgroud)

我的库中提供了更复杂的代码android-commons此处此处)。

绑定.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
}
Run Code Online (Sandbox Code Playgroud)