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:

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:

Isn't that neat?

--

--

Let’s imagine you need to provide a gradient background consisting of arbitrarily many colors to a View.

This can’t be done via regular drawable XML as a gradient within a shape can only define three colors: startColor, centerColor, endColor.

To reach our goal we will be using data binding.

We define an integer array in e.g. arrays.xml and fill it with the desired color resources:

Then we define a binding adapter to apply the colors in a gradient to the background of the View:

Now we can define the background colors in our layout XML (apply it to any View class you like):

Note, that we have to reference integer-array resources with @intArray in data binding expressions!

--

--

Sven Bendel

Founder and Senior Android Engineer. Crowdfunding addict. Trying hard to do the right thing and failing more often than not.