我有如下的spanableString
TextView contentNews = findViewById(R.id.text)
.........
.........
//article.getP() is HTML string
.........
CharSequence sequence = Html.fromHtml(article.getP(), this, null);
SpannableString spannableString = new SpannableString(sequence);
Linkify.addLinks(spannableString, Linkify.ALL);
URLSpan[] urlSpans = spannableString.getSpans(0, spannableString.length(), URLSpan.class);
for(URLSpan span : urlSpans){
Timber.d("LINK SPAN %s",span.getURL());
int start = spannableString.getSpanStart(span);
int end = spannableString.getSpanEnd(span);
int flag = spannableString.getSpanFlags(span);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick( View widget) {
Toast.makeText(NewReadingActivity.this, "Click " + span.getURL(), Toast.LENGTH_SHORT).show();
}
};
spannableString.setSpan(clickableSpan, start, end, flag);
}
contentNews.setText(spannableString);
但是当我单击它时,却没有执行任何操作,Log Timber也设法找到了如下URL:
01-16 20:42:55.560 mobile.android.tribun.daerah.jambi D/NewReadingActivity:418: LINK SPAN http://TRI-TIM.COM
答案 0 :(得分:0)
最后,我回答了我的问题。我所做的就是像这样更改代码段
CharSequence sequence = Html.fromHtml(article.getP(), this, null);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = stringBuilder.getSpans(0, sequence.length(), URLSpan.class);
for(URLSpan span : urls){
makeLinkClickable(stringBuilder, span);
}
contentNews.setText(stringBuilder);
contentNews.setMovementMethod(LinkMovementMethod.getInstance());
然后按如下所示进行操作
protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
public void onClick(View view) {
Intent intent = new Intent(NewReadingActivity.this, WebReadingActivity.class);
intent.putExtra(WebReadingActivity.EXTRA_URL_NEWS, span.getURL());
startActivity(intent);
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}