【法1】
/**
* 处理html文本超链接点击事件
* @param context
* @param tv
*/
public void textHtmlClick(Context context, TextView tv) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
CharSequence text = tv.getText();
if (textinstanceof Spannable) {
int end = text.length();
Spannable sp = (Spannable) text;
URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
SpannableStringBuilder style =new SpannableStringBuilder(text);
style.clearSpans();// should clear old spans
for (URLSpan url : urls) {
Log.i("lee", url.getURL());
MyURLSpan myURLSpan =new MyURLSpan(url.getURL(), context);
style.setSpan(myURLSpan, sp.getSpanStart(url),
sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
tv.setText(style);
}
}
private class MyURLSpanextends ClickableSpan {
private StringmUrl;
private ContextmContext;
MyURLSpan(String url, Context context) {
mContext = context;
mUrl = url;
}
@Override
public void onClick(View widget) {
Log.i("lee", mUrl);
Intent intent =new Intent(mContext, WebviewActivity.class);
intent.putExtra(WebviewActivity.LINK , mUrl);
intent.putExtra(WebviewActivity.TITLE, "近期面授详情");
startActivity(intent);
}
}
【法2】
/**
* 拦截超链接
* @param tv
*/
private void interceptHyperLink(TextView tv) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
CharSequence text = tv.getText();
if (textinstanceof Spannable) {
int end = text.length();
Spannable spannable = (Spannable) tv.getText();
URLSpan[] urlSpans = spannable.getSpans(0, end, URLSpan.class);
if (urlSpans.length ==0) {
return;
}
SpannableStringBuilder spannableStringBuilder =new SpannableStringBuilder(text);
// 循环遍历并拦截 所有http://开头的链接
for (URLSpan uri : urlSpans) {
String url = uri.getURL();
if (url.indexOf("http://") ==0) {
CustomUrlSpan customUrlSpan =new CustomUrlSpan(this,url);
spannableStringBuilder.setSpan(customUrlSpan, spannable.getSpanStart(uri),
spannable.getSpanEnd(uri), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
tv.setText(spannableStringBuilder);
}
}
class CustomUrlSpanextends ClickableSpan {
private Contextcontext;
private Stringurl;
public CustomUrlSpan(Context context,String url){
this.context = context;
this.url = url;
}
@Override
public void onClick(View widget) {
// 在这里可以做任何自己想要的处理
Intent intent =new Intent(context,WebviewActivity.class);
intent.putExtra(WebviewActivity.LINK,url);
intent.putExtra(WebviewActivity.TITLE, "近期面授详情");
context.startActivity(intent);
}
}