获取TextView中的url并设置点击事件

调用安卓默认的浏览器方法:

Intent intent = new Intent(Intent.ACTION_VIEW);

System.out.println("跳转到百度");
intent.setData(Uri.parse("http://www.baidu.com"));
// intent.setPackage("com.mx.browser");     intent.setPackage("com.uc.browser");   添加这一句是为了调用手机中的其他浏览器,前提是手机中安装了这些浏览器如遨游,uc等)

startActivity(intent);
如果获取textview中的url并设置点击事件,则按如下步骤:

1,textview的xml中添加    : android:autoLink="web" //或者all,根据需要

2,实现方法:(从网上摘抄)

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.
Log.i("LOG", "onClick url=" + urlSpan.getURL() );
Intent intent = new Intent(Intent.ACTION_VIEW);
System.out.println("点击的url:"+urlSpan.getURL());
intent.setData(Uri.parse(urlSpan.getURL()));       //使用默认浏览器打开url
// intent.setData(Uri.parse("www.baidu.com"));
// intent.setPackage("com.mx.browser");
startActivity(intent);
}
};
clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
}

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

4,最后,使用方法:

TextView tv = (TextView) findViewById(R.id.tv);
String url = "<a href=\"http://www.baidu.com\">www.baidu.com</a>"
+ "The Next Link is <a href=\"http://www.hao123.com\">hao123</a>";
tv.setText(getClickableHtml(url));
tv.setMovementMethod(LinkMovementMethod.getInstance());

总结:以上方法是从网上摘抄,但都少了 :tv.setMovementMethod(LinkMovementMethod.getInstance());

从而导致不能触发点击事件。点击  new ClickableSpan() 可以看到,只有实现LinkMovementMethod方法才能触发点击事件。

posted @ 2015-08-18 16:12  jkx  阅读(3610)  评论(0编辑  收藏  举报