0

I want to set the color code in a spannable string.

 SpannableString str= new SpannableString("Your new message ");
        str.setSpan(new ForegroundColorSpan("#00ff00", 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

I have tried the above code but it is not working.

  • Try below code SpannableString str= new SpannableString("Your new message "); str.setSpan(new ForegroundColorSpan(Color.GREEN), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); you can also try with str.setSpan(new ForegroundColorSpan(Color.parseColor("#00ff00")), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); –  Feb 25 '19 at 13:12
  • yes ,I know this way .but i have multiple color codes which i want to use.@AndroidTeam – PrajaktaParkhade Feb 25 '19 at 13:15
  • If the colors are dynamic, You should consider parsing color using `Color.parseColor("your_color_hex")`. Make sure you handle exceptions correctly. – Paresh P. Feb 25 '19 at 13:20

4 Answers4

1

Here color is an integer you should use :

Color.parseColor("#ff00ff00") 
Tristan N.
  • 26
  • 5
  • It's seems color must be ARGB so just add ff and it should work. Or use [this method](https://developer.android.com/reference/android/content/res/Resources.html#getColor(int,%20android.content.res.Resources.Theme)) to get colors from xml : – Tristan N. Feb 25 '19 at 13:25
  • 1
    no, `#RRGGBB` works too: `"Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'."` – pskink Feb 25 '19 at 13:28
1

I hope @Tristan's answer is correct. But if still there is a problem then try -

Spannable str= new SpannableString("Your new message ");
str.setSpan(new ForegroundColorSpan(Color.BLUE, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1

Please try this. It workes for me.

str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.geen_color)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

1

Your call to ForegroundColorSpan() misses the closing bracket and its argument should be an integer, not a string. A hex integer literal starts with '0x' in Java. So this snippet will make your code work:

new ForegroundColorSpan(0xff00ff00)

Parsing the string also works, of course, but it is not necessary.

HendrikFrans
  • 193
  • 9