我创建了一个自定义 URL 跨度,以使用 chrome 自定义选项卡打开链接。链接显示正确,我使用该Html.fromHtml()
功能。
在活动中,我将其用于 TextView:
content_txt_view = (TextView)findViewById(R.id.textView_news);
content_txt_view.setTransformationMethod(new LinkTransformationMethod());
content_txt_view.setMovementMethod(LinkMovementMethod.getInstance());
链接转换类如下所示:
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";
}
}
我本来希望当我单击链接时,我会收到 toast 消息……但似乎根本没有调用 OnClick 方法。