1

I have string called note. I put this code to change the color of specific words between two * * characters. It partially works fine. The issue I am facing is not coloring to yellow the exact words between * * after I inserted this symbol "➥ " (an example of phrase: This is a *good* book - it changes to yellow the last letter before word starts with * - a good instead of good). I need some help. I am newbie.

    if(note != null){
        int firstIndex = note.indexOf("*");
        if (firstIndex >= 0) {
            note = note.replaceFirst("[*]{1}", "");
            int secIndex = note.indexOf("*");
            if (secIndex >= 0) {
                note = note.replaceFirst("[*]{1}", "");

                String newString = "➥ "+note;
                Spannable spannable = new SpannableString(newString);
                spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD_ITALIC), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                txtnote.setText(spannable);
            }
        }
}  
Holly Ikki
  • 199
  • 1
  • 10

1 Answers1

1

Cause is length of string has been changed on 2 symbols, so indexes are changed too.

As for me it's not good way, but as quick solution:

    int removedSymbolCount = 0;
    if (firstIndex >= 0) {
        note = note.replaceFirst("[*]{1}", "");
        removedSymbolCount++;
        int secIndex = note.indexOf("*");
        if (secIndex >= 0) {
            note = note.replaceFirst("[*]{1}", "");
            removedSymbolCount++;
            String newString = "➥ "+note;
            Spannable spannable = new SpannableString(newString);
            spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), firstIndex + removedSymbolCount, secIndex + removedSymbolCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD_ITALIC), firstIndex + removedSymbolCount, secIndex + removedSymbolCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            txtnote.setText(spannable);
        }
    }

I think for better solution is possible to use Matcher and regex expressions.

Alexander
  • 857
  • 6
  • 10