2016-10-14 20 views
2

如何將我的對象字符串字段值與使用數據綁定的xml文件中的另一個字符串值進行比較?是否有可能在xml文件中這樣做,或者我應該在我的項目中使用@BindingAdapter註釋在某處創建一個方法? 下面是我到目前爲止嘗試過的,它沒有奏效。與字符串資源值進行比較,而不是與硬編碼的字符串值進行比較也是很好的做法。如何使用數據綁定在xml文件中比較字符串

<RadioGroup 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 

      <RadioButton 
       android:id="@+id/male" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:checked="@{user.gender.equalsIgnoreCase("male")}" 
       android:text="@string/male"/> 

      <RadioButton 
       android:id="@+id/female" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:checked="@{user.gender.equalsIgnoreCase("female")}" 
       android:text="@string/female"/> 

     </RadioGroup> 

感謝您的幫助。

回答

8

你幾乎正確。字符串常量不能使用通過在表達式後面引號中的XML雙引號內的雙引號,因此Android的數據綁定支持:

 <RadioButton 
      android:id="@+id/male" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:checked="@{user.gender.equalsIgnoreCase(`male`)}" 
      android:text="@string/male"/> 

這可以讓你用繩子一起混合使用單引號字符常量常量。

XML還允許使用單引號作爲屬性值,因此您可以在表達式中使用雙引號。這是比較常見的方法:

 <RadioButton 
      android:id="@+id/female" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:checked='@{user.gender.equalsIgnoreCase("female")}' 
      android:text="@string/female"/> 

您可以跳過整個事情並使用字符串資源或常量:

 <RadioButton 
      android:id="@+id/male" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:checked="@{user.gender.equalsIgnoreCase(@string/male)}" 
      android:text="@string/male"/> 

     <RadioButton 
      android:id="@+id/female" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:checked="@{user.gender.equalsIgnoreCase(StringConstants.FEMALE)}" 
      android:text="@string/female"/>