Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The onClick() of ClickableSpan is not working for URLSpan?

Tags:

android

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.

like image 714
Jiechao Wang Avatar asked Feb 06 '12 17:02

Jiechao Wang


1 Answers

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.

like image 148
Jiechao Wang Avatar answered Sep 24 '22 04:09

Jiechao Wang