Using gradient for styling text
Having an engaging and fancy user interface is essential for providing a delightful user experience. In some cases, this calls for using gradient colors. While Android’s styling system is pretty powerful, it lacks an out-of-the-box way to style a text using a gradient for coloring its text. Since at Plum we always try to explore new ways to achieve the best results, we had to come up with a solution!
CharacterStyle to the rescue!
Thankfully the android.text.style package contains enough tools for extending the already-provided styling capabilities. There’re many ways to extend it, but for this case, we’ll take a look at extending CharacterStyle to match our needs.
The key method of that abstract class is updateDrawState:
public abstract void updateDrawState(TextPaint tp);
This method has as a parameter the TextPaint that will be used in our TextView. Most importantly, the TextPaint can have a shader object for drawing. And for that, we’ll be using LinearGradient shader!
The code
Without further ado, here’s what we came up with:
Using it
The LinearGradientSpan can be used as any other character style:
val textView: TextView = findViewById(R.id.tv_hello)
val text = "Hello World!"
val purple = getColor(R.color.purple_200)
val teal = getColor(R.color.teal_200)
val spannable = text.toSpannable()
spannable[0..text.length] = LinearGradientSpan(text, text, purple, teal)
textView.text = spannable
It’s a relatively easy way to produce an interesting text effect.
While in a more real scenario (taken from Plum’s android application) the effect can have a more subtle effect:
Closing
As I’m not an expert in Graphics (let alone Android graphics 🤣), there should be plenty of optimizations that this utility class could receive. If you also want to build amazing things (and maybe improve the LinearGradientSpan!) check out our openings!