这是布尔数据
<variable
name="isSelected"
type="boolean" />
这就是我试图根据选择更改视图背景颜色的方式,在我的情况下,我应该根据选择更改文本视图颜色、背景颜色和图标颜色。
这是我尝试过的,但我在Android工作室中遇到了错误。
android:backgroundTint="@{isSelected ? ?attr/colorPrimaryVariant : ?attr/colorPrimary}"
这是一个错误
<expr> expected, got '?'
我不确定它是否仍然相关。我也遇到了同样的问题,并找到了解决方案。
- 您应该导入
R
类
<import type="com.example.test.R" />
- 现在,您可以在表达式中使用主题属性
"@{isSelected ? R.attr.colorPrimaryVariant : R.attr.colorPrimary}"
- 它还需要创建
BindingAdapter
,因为没有它会崩溃
类似这样的东西:
@BindingAdapter("backgroundAttr")
fun setBackgroundAttr(view: View, @AttrRes color: Int) {
view.setBackgroundColor(MaterialColors.getColor(view, color)
}
- 所以在XML中,它看起来是这样的
app:backgroundAttr="@{isSelected ? R.attr.colorPrimaryVariant : R.attr.colorPrimary}"