How to access a list of resources via data binding (and create nice gradient backgrounds along the road)

Sven Bendel
Apr 13, 2018

--

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

Senior Android Engineer @Photoroom. Founder. Crowdfunding addict. Trying hard to do the right thing and failing more often than not. https://proven.lol/286e9b