Last active
May 20, 2016 17:04
-
-
Save Peddro/70b716c41a23b14377c0a5a19181212b to your computer and use it in GitHub Desktop.
Change color of words in the middle of a text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);
Or you can add the same color to all the words:
String text = "This is a multi colored text";