How do I use databinding to combine a string from resources with a dynamic variable in XML?

Ignacio Perez picture Ignacio Perez · Aug 16, 2016 · Viewed 64.7k times · Source

I have a TextView which has a hardcoded string and I have a dynamic variable that I want to put at the end of this string. This is my code:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp">
    <TextView
        android:id="@+id/PeopleName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/Generic_Text"+"@{ Profile.name }" />


</LinearLayout>

I am having an issue with android:text="@string/Generic_Text"+"@{ Profile.name }" . The Generic_Text states " My Name is " then the Profile.name is dynamic and obviously changes from profile to profile. I want it so that the whole TextView output is My Name is {Profile.name}. Any help would be great.

Answer

Roman_D picture Roman_D · Aug 16, 2016

You can do this even simplier:

android:text= "@{@string/generic_text(profile.name)}"

you string should be like this:

<string name="generic_text">My Name is %s</string>

Edit:

  1. Of course you can use as many variables as you need:

    android:text= "@{@string/generic_text(profile.firstName, profile.secondName)}"
    
    <string name="generic_text">My Name is %1$s %2$s</string>
    
  2. It works just because it's designed in data binding. More in docs: https://developer.android.com/topic/libraries/data-binding/expressions#resources