0

I do spell checking, and want to show all wrong letters in red.

Like the user typed Mossosoppo and the correct word would be Missisippi. I would want to show the wrong letters in red.

I tried with SpannedString, SpannableString and SpannableStringBuilder. I also checked all examples Google would find. Nothing worked ( = maximum 1 letter was shown in red or all letters after a position).

And i tried all possible combinations of flags - SPAN_INCLUSIVE_INCLUSIVE, INCLUSIVE_EXCLUSIVE, EXCLUSIVE_INCLUSIVE, EXCLUSIVE_EXCLUSIVE.

This also didnt allow to use the same color in 2 places. The maximum i could see was a combination of different properties like color, bold, italic.

The interface to set a Span is setSpan(Object _what_, int _start_, int _end_, int _flags_).

Now this doesnt tell if it is possible to call it several times for the same property (color). Did anybody succeed to add more than 1 color span to a single string ?

If so i could digg again, maybe i had an error when i tested all possible combinations of flags. At the moment i am switching code to a LinearLayout with many TextViews where each TextView contains a single character. That should work. But it isnt elegant.

MatthiasL
  • 81
  • 6
  • See this: https://stackoverflow.com/a/6094346/4981406. You are able to make your own html String. – sajjad Dec 09 '20 at 14:15

1 Answers1

1

Ok, thanks to Sajjad i found the solution. It is possible to add 2 colors and more. However a ForegroundColorSpan may only be used once. So to set red 2 times you need 2 ForegroundColorSpan. If you reuse the same ForegroundColorSpan it does not work.

        SpannableStringBuilder fullstring =  new SpannableStringBuilder();

        ForegroundColorSpan fg_red = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan fg_black = new ForegroundColorSpan(Color.BLACK);
        ForegroundColorSpan fg_red2 = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan fg_black2 = new ForegroundColorSpan(Color.BLACK);


        SpannableString blackText = new SpannableString("This is black");
        blackText.setSpan(fg_black, 0, blackText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append (blackText);

        SpannableString redText = new SpannableString("red");
        redText.setSpan(fg_red, 0, redText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(redText);

        SpannableString blackText2 = new SpannableString("blackagain");
        blackText2.setSpan(fg_black2, 0, blackText2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(blackText2);

        SpannableString redText2 = new SpannableString("redagain");
        redText2.setSpan(fg_red2, 0, redText2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        fullstring.append(redText2);

        return fullstring;

// the returned string can then be used for TextView.setText(); 
MatthiasL
  • 81
  • 6