There are two ways to add a hyperlink to textView. The first method is to format your url in HTML, and the other is to set autolink so that the system can automatically identify the hyperlink.
The Code is as follows:
First Copy codeThe Code is as follows: public class MainActivity extends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
LinearLayout layout = new LinearLayout (this );
LayoutParams params = new LayoutParams (LayoutParams. MATCH_PARENT,
LayoutParams. MATCH_PARENT );
TextView textView = new TextView (this );
String html = "error: \ n ";
Html + = "<a href = 'HTTP: // www.baidu.com '> Baidu </a>"; // note that the Protocol number must be added here, that is, http ://.
// Otherwise, the system will think that the link is an activity, but the actual activity does not exist, and the program will crash.
CharSequence charSequence = Html. fromHtml (html );
TextView. setText (charSequence );
TextView. setMovementMethod (LinkMovementMethod. getInstance ());
Layout. addView (textView );
This. setContentView (layout, params );
}
Second Copy codeThe Code is as follows: public class MainActivity extends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
LinearLayout layout = new LinearLayout (this );
LayoutParams params = new LayoutParams (LayoutParams. MATCH_PARENT,
LayoutParams. MATCH_PARENT );
TextView textView = new TextView (this );
String html = "error: \ n ";
Html + = "www.baidu.com"; // even if HTTP is not added, it can be automatically recognized by the system.
TextView. setText (html );
TextView. setAutoLinkMask (Linkify. ALL );
TextView. setMovementMethod (LinkMovementMethod. getInstance ());
Layout. addView (textView );
This. setContentView (layout, params );
}
To sum up, a hyperlink is displayed in html, and the url must be fully written. The setAutoLinkMask (Linkify. ALL) can be automatically identified without writing completely.
You have to set setMovementMethod to redirect the two methods.
In addition, setAutoLinkMask not only recognizes hyperlinks, including phone numbers.