11

Is it possible to concat two dynamic strings using Data Binding?

My code looks like:

<TextView
                    android:id="@+id/text_view_activity_profile_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/image_view_activity_profile_small_photo"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="15dp"
                    android:text="@={userdata.firstName+' '+userdata.lastName}"
                    android:textColor="@color/white"
                    android:textSize="24sp" />

,but it is not the correct way : Error:(52, 42) The expression (firstNameUserdataCha) + (lastNameUserdata) cannot cannot be inverted: Two way binding with operator + supports only a single dynamic expressions.

Igor Mańka
  • 125
  • 1
  • 1
  • 7

4 Answers4

23

Try it like this instead

android:text='@{userdata.firstName+" "+userdata.lastName}' 

or alternately...

android:text='@{String.format("%s %s", userdata.firstName, userdata.lastName)}'
Carl Poole
  • 1,970
  • 2
  • 23
  • 28
  • 7
    This is right. It is not possible to use two-way data binding (`@={...}` instead of `@{...}`) with string concatenation. A third (and better) option is to use resource formatting to support multiple languages: `android:text="@{@string/name(userdata.firstName, userdata.lastName)}"` – George Mount Feb 27 '17 at 23:45
11

Below is recommended way.

It is also useful when you have localization/ multi language

Use string resource like this.

android:text="@{@string/generic_name(user.firstName,user.lastName)}"

and make string resource in strings.xml

<string name="generic_name">first name : %1$s and last name : %2$s</string>

You can check many other ways in this answer.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
2

It doesn't compile since you're using two-way data binding. Android DataBinding generated class won't be able to assign back the value of the TextView to userData since there are two variables used. You can use one-way data binding instead:

android:text='@{userData.firstName + " " + userData.lastName}'

If you really want to use two-way data binding, then make a custom converter for that.

Fadli
  • 976
  • 9
  • 24
0
                        <TextView
                        ..........
                        android:text='@{String.format("%s %s","+91", userInfo.mobile)}'
                        .............. />

try this if you want add multiple string

android:text='@{String.format("%s %s","+91", userInfo.mobile)}'

output: +91 0000000000

Sandeep Pareek
  • 1,636
  • 19
  • 21