String comparison on Android Data Binding

Ricardo Melo picture Ricardo Melo · Mar 14, 2016 · Viewed 10.8k times · Source

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}'

Answer

Sagar Chorage picture Sagar Chorage · Aug 29, 2017

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));
        }