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:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="some_colors">
<item>@color/color0</item>
<item>@color/color1</item>
<item>@color/color2</item>
<item>@color/color3</item>
<item>@color/color4</item>
</integer-array>
</resources>
Then we define a binding adapter to apply the colors in a gradient to the background of the View:
object ViewBindingAdapters {
@JvmStatic
@BindingAdapter("background_gradient_colors")
fun setBackgroundColors(view: View, colors: IntArray) {
view.background = GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT,
colors
)
}
}
Now we can define the background colors in our layout XML (apply it to any View class you like):
object ViewBindingAdapters {
@JvmStatic
@BindingAdapter("background_gradient_colors")
fun setBackgroundColors(view: View, colors: IntArray) {
view.background = GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT,
colors
)
}
}
Note, that we have to reference integer-array
resources with @intArray
in data binding expressions!