转载自:http://androidcocktail.blogspot.com/2014/03/android-spannablestring-example.html
The SpannableString in android is an excellent way to style strings in a TextView.
Put simply, it allows a TextView to provide different styles to different areas of text.
In the following example, we create in Activity to display a single TextView.
The TextView will use a SpannableString as its content, which will illustrate some of the available styles.
Here' what we're gonna do with the text :
- Make it larger
- Bold
- Underline
- Italicize
- Strike-through
- Colored
- Highlighted
- Show as superscript
- Show as subscript
- Show as a link
- Make it clickable.
The finished Activity will look like this :
So lets's dig in :). For simplicity, I'v limited myself to the onCreate() method of the Activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
A little explanation
The comments explain most of the stuff but here's a bit more.
The parameters for the setSpan() method are
- what : The type of Span.
- start : The inclusive start index for the Span.
- end : The exclusive end index for the Span.
- flag : Additional configuration. Refer to the constants here.
Notes :
- Multiple spans can be applied to the same area in a String. This has been shown above in the superscript span, where the text was both reduced in size and made superscript.
- The URLSpan and ClickableSpan both require the movementMethod of the TextView to be set as LinkMovementMethod.
- SpannableStrings are immutable. If this is a concern, use a SpannableStringBuilder.
- If you're using a string resource as the content of the TextView, some of the above styles can be declared in the resource itself. See this to check how.
- You could also use the Html.fromHtml method to create Spanned Strings using html tags. For an unofficial list of supported tags see this.
For any questions or suggestions, please leave comments.Adios :).