How to change the color of a part of a TextView in android ?

We can easily change the color of part of a textview using Spannable class in android. It will help you to specify the start index and end index within a string so that the text which remain within the index range can be set to span. We can hence change the properties of the spanned text.

Suppose you have a String like this

The quick brown fox jumps over the lazy dog  

and you want to change the colour of the word "quick" to red like this

The quick brown fox jumps over the lazy dog

 You may apply a span to "quick" by specifying the start index as 4 and end index as 9 like shown below

String text ="The quick brown fox jumps over the lazy dog";
Spannable spannable = new SpannableString(text);
spannable.setSpan(new ForegroundColorSpan(Color.RED), 4, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spannable,TextView.BufferType.SPANNABLE);

No comments:

Post a Comment