Search code examples
androidsubstringtextviewspannablestringandroid-color

Is there any way to change color of sub-string programmatically in Android?


I have a string resource

<string name="redesign_password_pattern">Your password must contain the following:\n\t&#8226; A minimum of 8 characters\n\t&#8226; At least 1 capital letter\n\t&#8226; At least 1 small letter\n\t&#8226; At least 1 number\n\t&#8226; At least 1 of the following special characters: !, @, #, $, *</string>

When i set this string to a TextView, it looks like this image

If the password entered by user contains a number, i want to change color of "At least 1 number" from the text and so on.

can it be achieved this way or do i need to follow another way?

So far, i tried the following way, but i don't know how to write start and end values for the string resource.

SpannableString spannableString =  new SpannableString(getString(R.string.redesign_password_pattern));
spannableString.setSpan(new ForegroundColorSpan(GREEN), 101, 130, 0);
pswFormat.setText(spannableString);

And i don't want to write 6 different TextViews. Please help me to find a way.

Thanks in advance.


Solution

  • Your code is fine, you are only missing the start and end and the color:

    spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 130, 147, 0);