ClickableSpan的onClick()不适用于URLSpan?

时间:2012-02-06 17:15:50

标签: android

在TextView中,我想在点击超链接时弹出一个toast,而不是在浏览器中打开相应的url。我使用下面的代码,但问题是onClick()方法似乎永远不会被调用!!:

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

有谁能告诉我我的代码有什么问题以及如何修复它?感谢。

1 个答案:

答案 0 :(得分:22)

实际上我的大四学生想出来了,我们需要在使用setSpan()添加我们自己的跨度之前删除原来的URLSpan

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

谢谢Damian。