36

I'm trying to make a string comparison with android XML data binding, but I'm not having the right results.

Evaluating my expression in code, I try notice.action == "continue" and this is false. 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. 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. 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. Did it this way:

android:textColor='@{ notice.action.equals("continue") ? @color/enabledPurple : @color/disabledGray}'
Ricardo Melo
  • 430
  • 1
  • 4
  • 12

4 Answers4

60

It can be do in two way :-

1. First way inside xml :-

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

2. Second way (programatically) Inside 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));
        }
ND1010_
  • 3,743
  • 24
  • 41
Sagar Chorage
  • 1,460
  • 12
  • 13
8

There is no need to import the String class into your layout file.

To check whether two strings have equal value or not equals() method should be used.

= 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 }"
Bhupendra Joshi
  • 233
  • 1
  • 5
  • 8
  • This may throw java.lang.reflect.InvocationTargetException: "String has already been defined as java.lang.String but trying to re-define as String" – esQmo_ Mar 04 '21 at 11:03
5

'continue' is char type, so it should be changed to String to compare with notice.action.

android:textColor="@{notice.action.equals(String.valueOf(`continue`)) ? @color/enabledPurple : @color/disabledGray }"
Jagpaw
  • 75
  • 1
  • 5
3

Try to add in xml

<data> <import type="String"/> </data> It may help to resolve .equals()

Chickin Nick
  • 517
  • 1
  • 6
  • 21