String string = "Change this color"
string.replace("this", "");
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);