Sven Bendel
A droid's life

A droid's life

Using String placeholders with data binding

Photo by Kira auf der Heide on Unsplash

Using String placeholders with data binding

Sven Bendel's photo
Sven Bendel
·Apr 27, 2018·

1 min read

Today I stumbled about one of these tiny things which — once you uncover them — immensely ease your life.

Consider a String with placeholders stored in your strings.xml:

<string name="some_string">Hello %1$s</string>

Now let's say we want to use that String directly in data binding. Before figuring out the following trick I would fetch the data from the attached ViewModel which would use String.format() to replace the placeholder with e.g. the user name.

Turns out there is a by far easier way to do this directly within the layout:

<TextView
          ...
          android:text="@{@string/some_string(user.name)}"/>

Isn't that neat?

 
Share this