16

In a TextView, I want to popup a toast whenever a hyperlink is clicked, instead of opening the corresponding url in a browser. I use the following code, but the problem here is the onClick() method seems never be called!!:

String source = "<a href=\"http://www.google.com\">link</a> ";

// Get SpannableStringBuilder object from HTML code
CharSequence sequence = Html.fromHtml(source, imgGetter, null);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);

// Get an array of URLSpan from SpannableStringBuilder object
URLSpan[] urlSpans = strBuilder.getSpans(0, strBuilder.length(), URLSpan.class);

// Add onClick listener for each of URLSpan object
for (final URLSpan span : urlSpans) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);

    strBuilder.setSpan(new ClickableSpan()
    {
    @Override
    public void onClick(View widget) {
        Toast toast = Toast.makeText(context, "well done! you click " + span.getURL(), Toast.LENGTH_SHORT);
        toast.show();           
    }       
    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

TextView t4 = (TextView) findViewById(R.id.text4);
t4.setText(strBuilder);
// No action if this is not set
t4.setMovementMethod(LinkMovementMethod.getInstance());

Can anyone tell me what's wrong with my code and how to fix it? Thanks.

Jiechao Wang
  • 922
  • 1
  • 15
  • 32

1 Answers1

29

Actually my senior figured out, we need to remove the original URLSpan before adding our own spans using setSpan()

    // The original URLSpan needs to be removed to block the behavior of browser opening
    strBuilder.removeSpan(span);

Thanks Damian.

Jiechao Wang
  • 922
  • 1
  • 15
  • 32
  • I was writing the solution until I saw your response. I started yesterday the fight against this problem. Your code give the last clue about my problem. – raultm Apr 17 '12 at 11:00
  • Nice. It works with removeSpan. This solution is what I was looking for. Thanks – Vito Valov Jan 28 '16 at 17:26