1

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.

Community
  • 1
  • 1
Lynx
  • 131
  • 9

2 Answers2

0

Yes, you can do this. The way I'd do this (since it's relatively simple stuff) is just with HTML. So you can do something like this...

TextView textView = (TextView) findViewById(R.id.textView); 

textView.setText(Html.fromHtml("<b><strike>" + twoFirstWords 
    + "</b></strike>" +  restOfTheSentence));

CommonsWare has a great blog post that list all of the tags that this supports that you can find here.

Alex K
  • 8,269
  • 9
  • 39
  • 57
  • Thank you for the comment. Right now, my majority of code is full of using Spannable String... So I really wanna know how to fix it using spannable string. If you know how, it will help a lot. Thank you for commenting here! :) – Lynx Jun 29 '15 at 08:54
  • @Lynx Sure. Then, you'd want to create one string, then set the spans for individual sections. I don't think you can combine two spans by appending them the way you did in your question. – Alex K Jun 29 '15 at 08:57
0

Ok, we have a conclusion. Thanks to pskink!

What I need to do, so the effect is not applied to content is using SPAN_EXCLUSIVE_EXCLUSIVE. Like below:

span1.setSpan(new StyleSpan(Typeface.BOLD), 0, twoFirstWords.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Lynx
  • 131
  • 9