Android: Is it possible to have multiple styles inside a TextView?
Posted
by Legend
on Stack Overflow
See other posts from Stack Overflow
or by Legend
Published on 2009-10-07T01:33:34Z
Indexed on
2010/05/30
23:12 UTC
Read the original article
Hit count: 382
I was wondering if its possible to set multiple styles for different pieces of text inside a TextView. For instance, I am setting the text as follows:
descbox.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);
Now, is it possible to have a different style for each text element? I mean bold for line1, normal for word1 and so on...
I found this http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext:
// Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text);
// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");
// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.
// Get the EditText's internal text storage
Spannable str = vw.getText();
// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
But it uses position numbers inside the text. Is there a cleaner way to do this?
© Stack Overflow or respective owner