Kalimah Apps Kalimah Apps - 1 year ago 81
Java Question

How to use SpannableString with Regex in android?

I am trying to color part of a string using spannableString and regular expressions in Android using this function:

public static String StringReplace(String source) {
String find = "ABC";
SpannableString replace = new SpannableString(find);
replace.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

String output = source.replace(find, replace);
return output;

Because the function replace() returns a string I am not able to get a colored string. My question is: what is the best way to color part of a text using regexp?

Answer Source

Updated 10th Sept - changes all occurrences of target string

Something generic like this will work:

public class SpanTest extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        String dispStr = "This has the string ABCDEF in it \nSo does this :ABCDEF - see!\nAnd again ABCD here";
        TextView tv = (TextView) findViewById(R.id.textView1);
        changeTextinView(tv, "ABC", Color.RED);

    private void changeTextinView(TextView tv, String target, int colour) {
        String vString = (String) tv.getText();
        int startSpan = 0, endSpan = 0;
        Spannable spanRange = new SpannableString(vString);

        while (true) {
            startSpan = vString.indexOf(target, endSpan);
            ForegroundColorSpan foreColour = new ForegroundColorSpan(colour);
            // Need a NEW span object every loop, else it just moves the span
            if (startSpan < 0)
            endSpan = startSpan + target.length();
            spanRange.setSpan(foreColour, startSpan, endSpan,