Set color of TextView span in Android Set color of TextView span in Android android android

Set color of TextView span in Android


Another answer would be very similar, but wouldn't need to set the text of the TextView twice

TextView TV = (TextView)findViewById(R.id.mytextview01);Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);TV.setText(wordtoSpan);


Here is a little help function. Great for when you have multiple languages!

private void setColor(TextView view, String fulltext, String subtext, int color) {    view.setText(fulltext, TextView.BufferType.SPANNABLE);    Spannable str = (Spannable) view.getText();    int i = fulltext.indexOf(subtext);    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);}


I always find visual examples helpful when trying to understand a new concept.

Background Color

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);textView.setText(spannableString);

Foreground Color

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);textView.setText(spannableString);

Combination

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);textView.setText(spannableString);

Further Study