ClickableSpan的onclick()不工作URLSpan?工作、ClickableSpan、onclick、URLSpan

2023-09-05 06:14:51 作者:萌面怪廋/檬面抄人

在一个TextView,我想弹出,而不是在浏览器中打开相应的网址,只要一个单击超链接敬酒。我用下面的code,但这里的问题是的onClick()方法似乎永远不会被调用!!:

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

谁能告诉我什么地方错了我的code和如何解决它?谢谢你。

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

推荐答案

其实我的高级想通了,我们需要用setSpan()加入我们自己的跨度之前删除原来的URLSpan

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.