0

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.

Dr Mido
  • 2,414
  • 4
  • 32
  • 72
Praveen
  • 220
  • 1
  • 2
  • 15
  • 2
    Maybe [this](https://stackoverflow.com/questions/4032676/how-can-i-change-the-color-of-a-part-of-a-textview) can help you – Tamir Abutbul Apr 19 '19 at 14:27

3 Answers3

0

Try this way:

<string name="hello_world_test">Your password must contain the following:\n\t&#8226;
  <font color= "#F44336" name="1">A minimum of 8 characters\n\t&#8226;</font>
  <font color= "#008577" name="2">At least 1 capital letter\n\t&#8226; </font>
  <font color= "#CDDC39" name="3">At least 1 small letter\n\t&#8226;</font>
  <font color= "#008577" name="4">At least 1 number\n\t&#8226;</font>
  <font color="#9C27B0"  name="5">At least 1 of the following special characters: !, @, #, $, *</font></string>

tv.setText(Html.fromHtml(getResources().getString(R.string.hello_world_test)));

enter image description here

Sultan Mahmud
  • 1,245
  • 8
  • 18
0

Yes, there is another way. Format the String with html's font-color property then pass it to the method Html.fromHtml(text)

 String text = "<font color=#cc0029>A minimum of 8 characters</font> <font color=#ffcc00>At least 1 capital letter</font>";
 yourtextview.setText(Html.fromHtml(text));
Ivan Abakumov
  • 128
  • 1
  • 13
0

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

spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 130, 147, 0);
forpas
  • 160,666
  • 10
  • 38
  • 76