Urlspan can not trigger Click on Textview

627 views Asked by At

I have spanableString like below

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);

but when I clicked it did nothing, Log Timber also managed to find the URLs like the following:

01-16 20:42:55.560 mobile.android.tribun.daerah.jambi D/NewReadingActivity:418: LINK SPAN http://TRI-TIM.COM
1

There are 1 answers

0
Nanda Z On BEST ANSWER

Finally i had an answer of my question. What i did is to change code snippet like this

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());

Then do action click like below

 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);
    }