Android captured text link click event

TextView display Html hyperlink conventional usage

  TextView myTextView = (TextView)findViewById(R.id.myTextView);
  String url = "<a href=\"http://baidu.com\">百度</a>";
  myTextView.setText(Html.fromHtml(url));
  // 这个必须设置,否则超链接点解没有效果
  myTextView.setMovementMethod(LinkMovementMethod.getInstance());

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: //baidu.com (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=\"http://baidu.com\">百度</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:

 myTextView.setText(getClickableHtml(url));

 // 设置超链接可点击
 myTextView.setMovementMethod(LinkMovementMethod.getInstance());

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    android:id="@+id/myTextView"
    android:autoLink="web" //
/>

Note:
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

Origin blog.csdn.net/u011118524/article/details/93738466