How to make textview gradient color in Android

Most of the time we developers use simple typical textviews in our app. But sometime we need to make this textview gradient color in order to look it more appealing or to follow the design pattern. To make the textview gradient color is bit tricky. Today I will show you how to do it.

So first of all we need to make our own custom LinearGradient shader. Set the multiple color in that it and then finally we apply it in our textview. As simple as it sounds.

Here is how we create shader:



TextView tv = findViewById(R.id.tv);
tv.setText("Our Text");
tv.setTextColor(startColor);
Shader textShader = new LinearGradient(0, 0, tv.getPaint().measureText(tv.getText().toString()), tv.getTextSize(),
                new int[]{startColor, endColor},
                new float[]{0, 1}, Shader.TileMode.CLAMP);
                

You see we are setting the textview text before we apply the shader, because we need the length of the text and textview. Also notice that we are setting the first/start color of the gradient otherwise it will look like kind of dull and faded out.

So guys this way we can achieve this. And if you want to use more color in gradient no problem. Add colors in the array. Just make sure that color array and the position array lengths are same. Here is the preview of the output:

In case if you are not willing to write these all by yourself no problem. I have made a library of it in github. You can find it here. Just apply and use it.

Thank you so much for visiting this page. Bye for now. See you next time with new tips.

0