Android captured text link click event

TextView display Html hyperlink conventional usage

  TextView myTextView = (TextView)findViewById(;
  String url = "<a href=\"\">百度</a>";
  // 这个必须设置,否则超链接点解没有效果

Interception hyperlink click event

The above operation, click on the hyperlink, the system will be encapsulated into Intent: Intent {act = android.intent.action.VIEW dat = http: // (has extras)}
'll find action is android. intent.action.VIEW, data activity http protocol, such as a browser.

If we want to intercept events point solution, we jump to the specified page, or do other logic, how to do?

  1. Get html type Spanned
  String url = "<a href=\"\">百度</a>";
  Spanned spannedHtml=Html.fromHtml(url);
  1. The key realization:
    The principle is that all of the URL is set to ClickSpan, then add control logic you want in its onClick event on it.
private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,
      final URLSpan urlSpan) {
    int start = clickableHtmlBuilder.getSpanStart(urlSpan);
    int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
    int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
    ClickableSpan clickableSpan = new ClickableSpan() {
          public void onClick(View view) {
            //Do something with URL here.
            // 如获取url地址,跳转到自己指定的页面
    clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);

private CharSequence getClickableHtml(Spanned spannedHtml) {
    SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
    URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
    for(final URLSpan span : urls) {
      setLinkClickable(clickableHtmlBuilder, span);
    return clickableHtmlBuilder;

3. clickSpan the set of html data, set to TextView in:


 // 设置超链接可点击

4. The last set of autoLink TextView attributes:
If no autoLink property, can not intercept a hyperlink click event, pro-test.

    android:autoLink="web" //

autoLink: a total of the following values: web, phone, map, email , all, none.
Namely: url connection, dial the telephone number to extract, map addresses, e-mail, all of the explanation is that all can support hyperlinks work, none is the default, no hyperlinks

Guess you like