I have made a custom URL span to use the chrome custom tab to open a link. The links are getting displayed correctly, I use the Html.fromHtml()
function.
In the activity I use this for the TextView:
content_txt_view = (TextView)findViewById(R.id.textView_news);
content_txt_view.setTransformationMethod(new LinkTransformationMethod());
content_txt_view.setMovementMethod(LinkMovementMethod.getInstance());
The linkstransformation class looks like this:
public class LinkTransformationMethod implements TransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
// Linkify.addLinks(textView, Linkify.WEB_URLS);
if (textView.getText() == null || !(textView.getText() instanceof Spannable)) {
return source;
}
Spannable text= new SpannableString(textView.getText());
URLSpan[] spans = text.getSpans(0, textView.length(), URLSpan.class);
for (int i = spans.length - 1; i >= 0; i--) {
URLSpan oldSpan = spans[i];
int start = text.getSpanStart(oldSpan);
int end = text.getSpanEnd(oldSpan);
String url = oldSpan.getURL();
text.removeSpan(oldSpan);
text.setSpan(new CustomTabsURLSpan(url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return text;
}
return source;
}
and the custom url span:
public class CustomTabsURLSpan extends URLSpan {
private Context context;
public CustomTabsURLSpan(String url) {
super(url);
Log.d("SensibleUrlSpan", "1");
}
public CustomTabsURLSpan(Parcel src) {
super(src);
Log.d("SensibleUrlSpan", "2");
}
@Override
public void onClick(View widget) {
Log.d("SensibleUrlSpan", "3");
String url = getURL();
Toast toast = Toast.makeText(context, "well done! you click ", Toast.LENGTH_SHORT);
toast.show();
// String url = "http://www.google.com";
}
}
I would have expected that when I click on the link, I will get the toast message...But it seems the OnClick method is not called at all.
The classes below implement the desired behaviour:
CustomClickURLSpan.java
CustomTabsOnClickListener.java
A Utility class with the linkifyUrl methods that creates Spans for the URLs
Finally, invoke those classes to linkify the text:
The helper classes used are available on the Github Demo: CustomTabsHelper and CustomTabsActivityHelper