Textview is used to display text. Sometimes you need to set individual words in textview as hyperlinks, or set the color and font of individual words. Then you need to use the spannable object, you can use the spannable object to implement the above settings.
:
Activity Code:
- Package com. Zhou. activity;
- Import Android. App. activity;
- Import Android. Graphics. color;
- Import Android. OS. Bundle;
- Import Android. Text. spannable;
- Import Android. Text. spannablestring;
- Import Android. Text. spanned;
- Import Android. Text. method. linkmovementmethod;
- Import Android. Text. style. backgroundcolorspan;
- Import Android. Text. style. foregroundcolorspan;
- Import Android. Text. style. stylespan;
- Import Android. Text. style. urlspan;
- Import Android. widget. textview;
- Public class textviewlinkactivity extends activity {
- Textview mytextview;
- @ Override
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Mytextview = (textview) This. findviewbyid (R. Id. mytextview );
- // Create a spannablestring object
- Spannablestring sp = new spannablestring ("this sentence contains a Baidu hyperlink, highlighted, or in italic .");
- // Set the hyperlink
- Sp. setspan (New urlspan ("http://www.baidu.com"), 5, 7,
- Spanned. span_exclusive_exclusive );
- // Set highlight style 1
- Sp. setspan (New backgroundcolorspan (color. Red), 17, 19, spannable. span_exclusive_exclusive );
- // Set highlight style 2
- Sp. setspan (New foregroundcolorspan (color. Yellow), 20, 24, spannable. span_exclusive_inclusive );
- // Set italics
- Sp. setspan (New stylespan (Android. Graphics. typeface. bold_italic), 27, 29, spannable. span_exclusive_inclusive );
- // Set the spannablestring object to textview.
- Mytextview. settext (SP );
- // Set textview to clickable
- Mytextview. setmovementmethod (linkmovementmethod. getinstance ());
- }
- }