Android TextView, including strikethrough, hyperlinks, colors, and fonts, androidtextview
There are several ways to add special effects to TextView:
First, use the android: autolink attribute to automatically apply the effect, for example:
Java code
- <TextView xmlns: android = "http://schemas.android.com/apk/res/android"
- Android: id = "@ + id/text1"
- Android: layout_width = "match_parent"
- Android: layout_height = "match_parent"
- Android: autoLink = "all"
- Android: text = "@ string/link_text_auto"
- />
Second, use the <a> label in the text, for example:
Java code
- <String name = "link_text_manual"> <B> text2: </B> This is some other
- Text, with a <a href = "http://www.google.com"> link </a> specified
- Via an & lt; a & gt; tag. Use a \ "tel: \" URL
- To <a href = "tel: 4155551212"> dial a phone number </a>
- </String>
The third and second types are actually the same, except that the text is changed to JAVA code, such:
Java code
- TextView t3 = (TextView) findViewById (R. id. text3 );
- T3.setText (
- Html. fromHtml (
- "<B> text3: </B> Text with a" +
- "<A href = \" http://www.google.com \ "> link </a>" +
- "Created in the Java source code using HTML ."));
- T3.setMovementMethod (LinkMovementMethod. getInstance ());
Fourth, the first three can be said to be automatic, and the fourth is pure "Manual. Create a SpanableString and create one or more spans on it to achieve a wide range of results. Example:
Java code
- SpannableString ss = new SpannableString ("text4: Click here to dial the phone .");
- Ss. setSpan (new StyleSpan (Typeface. BOLD), 0, 6, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE );
- Ss. setSpan (new URLSpan ("tel: 4155551212"), 13, 17, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE );
- TextView t4 = (TextView) findViewById (R. id. text4 );
- T4.setText (ss );
- T4.setMovementMethod (LinkMovementMethod. getInstance ());
For the complete code, see ApiDemo. The following are some notes:
. SetMovementMethod. This method is used to respond to user events. If you click a phone number, the dialing page is displayed. If you do not execute this method, it will not respond to the event, even if the text is already an underline blue.
. Spanned. SPAN_EXCLUSIVE_EXCLUSIVE: This is the flag that needs to be specified during setSpan. It means that I tried it for a long time and didn't try it. I had a sleep. This morning I suddenly thought about it. It is used to identify whether to apply new characters before and after the text within the Span range. Spanned. SPAN_EXCLUSIVE_EXCLUSIVE (not included before and after), Spanned. SPAN_INCLUSIVE_EXCLUSIVE (included first, not included later), Spanned. SPAN_EXCLUSIVE_INCLUSIVE (not included earlier, not included later), Spanned. SPAN_INCLUSIVE_INCLUSIVE (both before and after ). You can see the following:
Comparison
Below