实现 Android 文本链接的 4 种方法

  1. 使用 TextView android:autoLink 属性,能自动识别文本中的 URLs 和 电话号码;
  2. 使用 <a> 标签标记字符串中的链接,比如

     <a href="http://www.google.com">link</a>
     <a href="tel:4155551212">dial a phone number</a>
    
  3. 使用 SpannableStringURLSpan 标记字符串;以上三种方法适用于固定(fixed)字符串,如果是动态字符串资源,比如来自网络;

  4. 从 HTML 中导入字符串:setText(Html.fromHtml(String html)).

      // text4 shows creating text with links from HTML in the Java
      // code, rather than from a string resource.  Note that for a
      // fixed string, using a (localizable) resource as shown above
      // is usually a better way to go; this example is intended to
      // illustrate how you might display text that came from a
      // dynamic source (eg, the network).
    
      TextView t4 = (TextView) findViewById(R.id.text4);
      t4.setText(
          Html.fromHtml(
              "<b>text4: Constructed from HTML programmatically.</b>  Text with a " +
              "<a href=\"http://www.google.com\">link</a> " +
              "created in the Java source code using HTML."));
      t4.setMovementMethod(LinkMovementMethod.getInstance());
    

代码来源 Android API Demos: AndroidLink.java