Skip to content

Instantly share code, notes, and snippets.

@Peddro
Last active May 20, 2016 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Peddro/70b716c41a23b14377c0a5a19181212b to your computer and use it in GitHub Desktop.
Save Peddro/70b716c41a23b14377c0a5a19181212b to your computer and use it in GitHub Desktop.
Change color of words in the middle of a text.
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
public class SpannableStringColor {
private final String text;
private final Spannable colorizedString;
public SpannableStringColor(String text) {
this.text = text;
this.colorizedString = new SpannableStringBuilder(text);
}
private SpannableStringColor(Spannable spannableString, String text) {
this.text = text;
this.colorizedString = spannableString;
}
public Spannable colorizeAll(int color, String... texts) {
for(String word : texts) {
int start = this.text.indexOf(word);
if (start > -1) {
colorizedString.setSpan(new ForegroundColorSpan(color), start, start + word.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
return colorizedString;
}
public SpannableStringColor colorize(int color, String word) {
int start = this.text.indexOf(word);
if (start > -1) {
colorizedString.setSpan(new ForegroundColorSpan(color), start, start + word.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
return new SpannableStringColor(colorizedString, text);
}
public Spannable toSpan() {
return colorizedString;
}
}
@Peddro
Copy link
Author

Peddro commented May 20, 2016

Usage:

You can have each word with a color:

String text = "This is a multi colored text";
int red = getResources().getColor(android.R.color.holo_red_light);
int blue = getResources().getColor(android.R.color.holo_blue_bright);
int green = getResources().getColor(android.R.color.holo_green_light);

Spannable colorizedText = new SpannableStringColor(text)
.colorize(green, "multi")
.colorize(red, "colored")
.colorize(blue, "text")
.toSpan();

textview.setText(colorizedText);

Or you can add the same color to all the words:
String text = "This is a multi colored text";

Spannable colorizedSubtitle = new SpannableStringColor(text)
.colorizeAll(orange, "multi", "colored", "text");

textview.setText(colorizedText);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment