具有主题属性的数据绑定 [英] Data Binding with theme attributes

查看:73
本文介绍了具有主题属性的数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying out the new Android Databinding Library and I wanted to set the background color of ToolBar using a binding. By default the color should be colorPrimary (from the theme).

在使用DataBinding之前,我的toolBar看起来像

Before I was using DataBinding, my toolBar looked like

 <android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        />

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

After adding a binding, I wanted to set its background to colorPrimary if no color is bound - I'm using ternary operator for this (as mentioned in the guide) - but it causes an error, as theme attributes also have a "?" operator before their names. The compiler thinks I'm starting a new ternary operation.

<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 }"
        />

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

So is there a way I can access theme attributes inside a binding operation? Thanks!

修改

我知道我可以以编程方式获取colorPrimary属性,并通过Java代码将其绑定.但是我只是想知道是否存在基于Xml的解决方案.

I know I can get the colorPrimary attribute programmatically and bind it through java code. But I'm just wondering if there's an Xml-based solution for this or not.

推荐答案

答案有点迟了,但也许对某人有帮助.

The answer is a bit late, but maybe it helps someone.

要访问数据绑定中的主题属性,可以使用以下方法:

For accessing theme attributes in data binding, you can use this:

(假设clickableBoolean变量)

android:background="@{clickable ? android.R.attr.selectableItemBackground : android.R.color.transparent}"

不需要其他绑定适配器或其他东西.

No additional binding adapters or another things needed.

这篇关于具有主题属性的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆