如何使用数据绑定将我的对象字符串字段值与 xml 文件中的另一个字符串值进行比较?是否可以在 xml 文件中执行此操作,或者我应该在项目中的某个位置创建一个方法@BindingAdapter
注解?
以下是我迄今为止尝试过的方法,但没有成功。最好与字符串资源值进行比较,而不是与硬编码的字符串值进行比较。
<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>
感谢帮助。
你几乎是正确的。字符串常量不能在 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"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)