Codementor Events

How to create a Spannable TextView color

Published Jun 09, 2019
 How to create a Spannable TextView color

Hi today I'll show you how to create a spannable textview color. Let's goo 😃

First of all ,A spannable TextView can be used in Android to highlight a particular portion of text with a different color, style, size, and/or click event in a single TextView widget.

Consider that you have defined a TextView as follows:

TextView txtView =findViewById(R.id.txtView);

After that you can apply different highlighting to it as shown below:
Spannable color: In order to set a different color to some portion of text, a ForegroundColorSpan can be used, as shown in the following example:

Spannable spannable = new SpannableString(firstWord+lastWord); spannable.setSpan(new ForegroundColorSpan(firstWordColor), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan(new ForegroundColorSpan(lastWordColor), firstWord.length(), firstWord.length()+lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textview.setText( spannable );

Output created by the code above
T8Bkp.png

Thanks for reading my tip and I hope to be happy.

Ahmed S Issa

Discover and read more posts from Ahmad S Issa
get started