basaya basaya - 3 years ago 148
Android Question

String.replace then change the color of the replaced word

String string = "Change this color"
string.replace("this", "");


How to change the color of the word "this" by replace() method?

Answer Source

replace() cannot be used to change the appearance of a string, Neha's answer is also correct, but a better way to do it is using the Spannable class, following function changes the color of String search in String text and returns a spannable object,

 private Spannable getSpannableText(String text, String search, Context context) {
    int initialOffset = text.toLowerCase().indexOf(search.toLowerCase(), 0);
    Spannable spannableText = new SpannableString(text);
    for (int ofs = 0; ofs < text.length() && initialOffset != -1; ofs = initialOffset + 1) {
        initialOffset = text.toLowerCase().indexOf(search.toLowerCase(), ofs);
        if (initialOffset == -1) {
            break;
        } else {
            //highlighting with color red
            spannableText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.red)), initialOffset, initialOffset + search.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableText;
}

You can then use it as follows,

 tv_text.setText(getSpannableText("Change this color","this", context), TextView.BufferType.SPANNABLE);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download