赞
踩
终于解决了这个问题,记录一下
activity代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv);
String str ="单击打开 百度首页";
textView.setText(Html.fromHtml(str));
interceptHyperLink(textView);
}
/**
* 拦截超链接
*
* @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);
SpannableStringBuilder spannableStringBuilder =setTextLinkOpenByWebView(this, text.toString());
// 循环遍历并拦截 所有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);
}
}
public static SpannableStringBuildersetTextLinkOpenByWebView(final Context context, String answerString) {
if (!TextUtils.isEmpty(answerString)) {
Spanned htmlString = Html.fromHtml(answerString);
if (htmlStringinstanceof SpannableStringBuilder) {
SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) htmlString;
// 取得与a标签相关的Span
Object[] objs = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), URLSpan.class);
if (null != objs && objs.length !=0) {
for (Object obj : objs) {
int start = spannableStringBuilder.getSpanStart(obj);
int end = spannableStringBuilder.getSpanEnd(obj);
if (objinstanceof URLSpan) {
//先移除这个Span,再新添加一个自己实现的Span。
URLSpan span = (URLSpan) obj;
final String url = span.getURL();
spannableStringBuilder.removeSpan(obj);
spannableStringBuilder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Intent intent =new Intent(context, WebViewActivity.class);
context.startActivity(intent);
}
}, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
return spannableStringBuilder;
}
}
return new SpannableStringBuilder(answerString);
}
自定义ClickableSpan子类的CustomUrlSpan的主要代码如下所示:
public class CustomUrlSpan extends 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.WEB_URL,url);
context.startActivity(intent);
}
}
具体的布局就是一个textview,另外webview代码很简单,不贴了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。