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:
- PackageCom. Zhou. activity;
- ImportAndroid. App. activity;
- ImportAndroid. Graphics. color;
- ImportAndroid. OS. Bundle;
- ImportAndroid. Text. spannable;
- ImportAndroid. Text. spannablestring;
- ImportAndroid. Text. spanned;
- ImportAndroid. Text. method. linkmovementmethod;
- ImportAndroid. Text. style. backgroundcolorspan;
- ImportAndroid. Text. style. foregroundcolorspan;
- ImportAndroid. Text. style. stylespan;
- ImportAndroid. Text. style. urlspan;
- ImportAndroid. widget. textview;
- Public ClassTextviewlinkactivityExtendsActivity {
- Textview mytextview;
- @ Override
- Public VoidOncreate (bundle savedinstancestate ){
- Super. Oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Mytextview = (textview)This. Findviewbyid (R. Id. mytextview );
- // Create a spannablestring object
- Spannablestring sp =NewSpannablestring ("this sentence contains Baidu hyperlink, highlighted, or in italic .");
- // Set the hyperlink
- Sp. setspan (NewUrlspan ("http://www.baidu.com"), 5, 7,
- Spanned. span_exclusive_exclusive );
- // Set highlight style 1
- Sp. setspan (NewBackgroundcolorspan (color. Red), 17, 19, spannable. span_exclusive_exclusive );
- // Set highlight style 2
- Sp. setspan (NewForegroundcolorspan (color. Yellow), 20, 24, spannable. span_exclusive_inclusive );
- // Set italics
- Sp. setspan (NewStylespan (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 ());
- }
- }