简体   繁体   English

Android 数据绑定上的字符串比较

[英]String comparison on Android Data Binding

I'm trying to make a string comparison with android XML data binding, but I'm not having the right results.我正在尝试与 android XML 数据绑定进行字符串比较,但我没有得到正确的结果。

Evaluating my expression in code, I try notice.action == "continue" and this is false.评估我在代码中的表达,我尝试notice.action == "continue" ,这是错误的。 And in data binding, this is false too, of course.在数据绑定中,这当然也是错误的。

android:textColor='@{ notice.action == "continue" ? @color/enabledPurple : @color/disabledGray}'

It only gets true when I do notice.action.equals("continue") by code.只有当我通过代码执行notice.action.equals("continue")时,它才会notice.action.equals("continue") true。 This is the intended behavior.这是预期的行为。 My problem is that I can't accomplish this with data binding expressions, because it won't run methods like equals .我的问题是我不能用数据绑定表达式来完成这个,因为它不会运行像equals这样的方法。 What can I do to replace the comparison expression with another one that works?我该怎么做才能用另一个有效的比较表达式替换比较表达式?

I'm using this guide .我正在使用本指南

Edit: I was wrong, methods are allowed in XML.编辑:我错了,XML 中允许使用方法。 Did it this way:是这样做的:

android:textColor='@{ notice.action.equals("continue") ? @color/enabledPurple : @color/disabledGray}'

It can be do in two way :-它可以通过两种方式完成:-

1. First way inside xml :- 1. xml 中的第一种方式:-

    android:textColor="@{notice.action.equals(`continue`) ? @color/enabledPurple : @color/disabledGray }"

2. Second way (programatically) Inside xml :- 2.第二种方式(以编程方式)在xml中:-

app:setColor="@{notice.action}" 
inside activity or custom class : -    
    @BindingAdapter("setColor")
        public static void setTextColor(TextView textView, String s) {

             Context context = textView.getContext();

        textView.setTextColor(s.equals("continue") ? context.getResources().getColor(R.color.enabledPurple) : context.getResources().getColor(R.color.disabledGray));
        }

There is no need to import the String class into your layout file.无需将 String 类导入到布局文件中。

To check whether two strings have equal value or not equals() method should be used.要检查两个字符串是否具有相等的值,应使用equals()方法。

= is used to check the whether the two strings refer to the same reference object or not. =用于检查两个字符串是否指向同一个引用对象。

Solution:解决方案:

android:textColor="@{notice.action.equals(`continue`) ? @color/enabledPurple : @color/disabledGray }"

Try to add in xml尝试在xml中添加

<data> <import type="String"/> </data> It may help to resolve .equals() <data> <import type="String"/> </data>可能有助于解决.equals()

'continue' 是 char 类型,因此应该将其更改为 String 以与 notice.action 进行比较。

android:textColor="@{notice.action.equals(String.valueOf(`continue`)) ? @color/enabledPurple : @color/disabledGray }"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM