簡體   English   中英

如何在android數據綁定中的三元運算符中提及屬性(?attr)?

[英]How to mention attribute(?attr) inside ternary operator in android data binding?

這是布爾數據

  <variable
                name="isSelected"
                type="boolean" />

這就是我嘗試根據選擇更改視圖背景顏色的方式,在我的情況下,我應該根據選擇更改文本視圖顏色、背景顏色和圖標顏色。

這是我嘗試過的,但我在 Android Studio 中遇到錯誤。

        android:backgroundTint="@{isSelected ? ?attr/colorPrimaryVariant : ?attr/colorPrimary}"

這是一個錯誤

<expr> expected, got '?'

我不確定它是否仍然相關。 我遇到了同樣的問題並找到了解決方案。

  1. 你應該導入你的R

<import type="com.example.test.R" />

  1. 現在,您可以在表達式中使用主題屬性

"@{isSelected ? R.attr.colorPrimaryVariant : R.attr.colorPrimary}"

  1. 它還需要創建BindingAdapter因為沒有它會崩潰

像這樣的東西:

@BindingAdapter("backgroundAttr")
fun setBackgroundAttr(view: View, @AttrRes color: Int) {
    view.setBackgroundColor(MaterialColors.getColor(view, color)
}
  1. 所以在 XML 中,它看起來像這樣

app:backgroundAttr="@{isSelected ? R.attr.colorPrimaryVariant : R.attr.colorPrimary}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM