39
Tweet o = tweets.get(position);

TextView tt = (TextView) v.findViewById(R.id.toptext);
//TextView bt = (TextView) v.findViewById(R.id.bottomtext);         

EditText bt =(EditText)findViewById(R.id.bottomtext);
bt.setText(o.author);
Spannable spn = (Spannable) bt.getText();
spn.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC)
, 0, 100, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  

//bt.setText(o.author);    
tt.setText(o.content);

I'm setting twitter data in my Android application. I want to make the font bold and italic using Spannable but it does not work, giving an error. How can I do it?

j0k
  • 22,600
  • 28
  • 79
  • 90
baran
  • 423
  • 1
  • 4
  • 5
  • it gives has stopped unexpectedly error. normally code working but I want to make the font bold . ıt gıves this error. – baran Feb 12 '13 at 19:41
  • pls post LogCat output with the exception. Most likely you're trying to apply the span beyond the text end - use actual length instead of 100 – Asahi Feb 12 '13 at 19:53
  • this method may be helpful https://stackoverflow.com/a/44255840/3496570 – Zar E Ahmer May 30 '17 at 07:24

3 Answers3

78

I want to make the font bold and ıtalic with spannable

for this u will need to make o.content text as SpannableString then set it to TextView as :

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

EDIT : you can also use Html.fromHtml for making text Bold and Italic in textview as :

tt.setText(Html.fromHtml("<strong><em>"+o.content+"</em></strong>"));
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
2

The easy way to create a spannable text bold and italic to set into your TextView is using the method Html.fromHtml():

and using the html elements <b> and <i>

myTextView.setText(Html.fromHtml("<b><i>my text bold and italic!</i></b>"));

or the html elements <strong> and <em>

   myTextView.setText(Html.fromHtml("<strong><em>my text bold and italic!</em></strong>"));
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
1
SpannableString hint = new SpannableString(o.content.toString());

Font size

hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

Font family

hint.setSpan(new TypefaceSpan("sans-serif"), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

italic

hint.setSpan(new StyleSpan(Typeface.ITALIC), 0, s.length(), 0);

color

hint.setSpan(new ForegroundColorSpan(Color.GRAY), 0, hint.length(), 0);

bold

hint.setSpan(new StyleSpan(Typeface.BOLD), 0, hint.length(), 0);

Reference link: https://www.programcreek.com/java-api-examples/index.php?api=android.text.style.RelativeSizeSpan

CleanCoder
  • 332
  • 3
  • 14