简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM