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.