0

我有像下面这样的 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
4

1 回答 1

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);
    }
于 2019-01-22T02:45:29.703 回答