Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

TextView 添加超链接的两种实现方式

編輯:關於 Android 程式設計

在 TextView 中添加可点击的超链接,主要有两种实现思路:一种是通过 HTML 格式化网址,另一种是设置 autoLink 让系统自动识别。下面分别来看。

第一种:使用 HTML 格式化

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 = "有问题:\n";
        html += "<a href='https://www.baidu.com'>百度一下</a>"; // 注意这里必须加上协议号,即 https://
        // 否则,系统会以为该链接是 activity,而实际这个 activity 不存在,程序就崩溃。
        CharSequence charSequence = Html.fromHtml(html);
        textView.setText(charSequence);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        layout.addView(textView);
        this.setContentView(layout, params);
    }
}

第二种:使用 setAutoLinkMask 自动识别

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 = "有问题:\n";
        html += "www.baidu.com"; // 这里即使不加协议号 https://,也能被系统自动识别出来。
        textView.setText(html);
        textView.setAutoLinkMask(Linkify.ALL);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        layout.addView(textView);
        this.setContentView(layout, params);
    }
}

小结

总结一下:用 HTML 方式显示超链接时,必须写完整的 url(含 https://);而用 setAutoLinkMask(Linkify.ALL) 则不用写全,系统也能自动识别出来。

需要注意的是,这两种方法都得设置一下 setMovementMethod,链接才会真正跳转。另外 setAutoLinkMask 不仅能识别超链接,还能识别电话号码之类的文本内容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved