I am trying to give some style effect (like bold, strikethrough) to the first two words in a string. The way I am doing it is inspired by this thread.
String[] tokens = text.split(" ");
String twoFirstWords = tokens[0] + " " + tokens[1]; //two first words
String content = text.replaceFirst(twoFirstWords, " "); //the rest
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString span1 = new SpannableString(twoFirstWords);
SpannableString span2 = new SpannableString(content);
span1.setSpan(new StyleSpan(Typeface.BOLD), 0, twoFirstWords.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
span1.setSpan(new StrikethroughSpan(),0, twoFirstWords.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE );
span1.setSpan(new CustomTypefaceSpan("", fontFirst), 0, twoFirstWords.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
span2.setSpan(new CustomTypefaceSpan("", fontContent), 0, content.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
builder.append(span1);
builder.append(span2);
textView.setText(builder, TextView.BufferType.SPANNABLE);
Based on code above, I am trying to give BOLD and Strikethrough effect only to the two first words.. However, those effects are also applied to the content.
This code worked fine when I applied style for two last words in a string, but keep failing when using first words. I suspect this is because of wrong start and end of .SetSpan
(Or maybe that is not the case)... I am also still clueless at finding the right index for start and end.. Anyone can help me to fix this issue? Thank you.