数据绑定与主题属性

sud*_*wan 11 data-binding android android-theme

我正在尝试新的Android 数据绑定库,我想使用绑定设置ToolBar的背景颜色.默认情况下,颜色应为colorPrimary(来自主题).

在我使用DataBinding之前,我的工具栏看起来像

 <android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        />
Run Code Online (Sandbox Code Playgroud)

添加一个绑定后,我想将其背景设置为colorPrimary如果没有绑定颜色 - 我正在使用三元运算符(如指南中所述) - 但它会导致错误,因为主题属性也有一个"?" 操作员在他们的名字前 编译器认为我正在开始新的三元运算.

<data>
    <variable name="toolBarBackgroundColor" type="int"/>
</data>
...
<android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@{toolBarBackgroundColor!=0? toolBarBackgroundColor: ?attr/colorPrimary }"
        />
Run Code Online (Sandbox Code Playgroud)

那么有没有办法可以在绑定操作中访问主题属性?谢谢!

编辑

我知道我可以通过编程方式获取colorPrimary属性并通过java代码绑定它.但我只是想知道是否有基于Xml的解决方案.

mao*_*eng 2

寻找使用数据绑定的方法?这是我所做的测试。首先,创建自定义绑定适配器方法:

@BindingAdapter({"app:customPrimaryBackground"})
public static void setCustomPrimaryBackground(View v, int resId) {
    TypedValue typedValue = new TypedValue();
    Context context = v.getContext();
    if (resId == 0) {
        context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        v.setBackgroundResource(typedValue.resourceId);
    } else {
        // Check the given resource ID is a color or drawable
        context.getResources().getValue(resId, typedValue, true);
        Drawable drawable;
        if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
            // It's a color
            drawable = new ColorDrawable(typedValue.data);
        } else {
            drawable = ContextCompat.getDrawable(context, resId);
        }

        v.setBackground(drawable);
    }
}
Run Code Online (Sandbox Code Playgroud)

其次,您的绑定 xml 布局:

<data>
    <variable name="toolBarBackgroundColor" type="int"/>
</data>
...
<android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:customPrimaryBackground="@{toolBarBackgroundColor}"
/>
Run Code Online (Sandbox Code Playgroud)