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.

1
  • set your textview in your java code with setText. Commented Feb 27, 2017 at 15:34

4 Answers 4

23

Try it like this instead

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

or alternately...

android:text='@{String.format("%s %s", userdata.firstName, userdata.lastName)}'
Sign up to request clarification or add additional context in comments.

1 Comment

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)}"
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.

Comments

3

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.