【问题标题】:How to compare strings in xml file using databinding如何使用数据绑定比较xml文件中的字符串
【发布时间】:2017-02-24 05:19:18
【问题描述】:

如何使用数据绑定将我的对象字符串字段值与 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>

感谢您的帮助。

【问题讨论】:

    标签: android data-binding android-databinding


    【解决方案1】:

    你说得几乎是正确的。字符串常量不能在 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"/>
    

    【讨论】:

    • android:checked="@{user.gender.equalsIgnoreCase(StringConstants.FEMALE)}" 不起作用
    • 我导入了我的接口并在其中放置了一个字符串常量,在这种情况下项目构建失败
    • 我赞成其中一个答案。您必须在 data 部分中使用 import 语句。
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2022-07-22
    • 2020-12-02
    相关资源
    最近更新 更多