public class CustomTabsURLSpan extends URLSpan {
public CustomTabsURLSpan(String url) {
super(url);
}
public CustomTabsURLSpan(Parcel src) {
super(src);
}
@Override
public void onClick(View widget) {
String url = getUrl();
//attempt to open in CustomTabs, if that fails call super.onClick(widget);
}
}
创建自定义转换方法,该方法将设置链接的跨度:
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);
String stringText = textView.getText().toString();
Spannable text = (Spannable) textView.getText();
URLSpan[] spans = text.getSpans(0, textView.length(), URLSpan.class);
for (int i = spans.length - 1; i >= 0; i--) {
URLSpan oldSpan = spans[i];
text.removeSpan(oldSpan);
String url = oldSpan.getURL();
int startIndex = stringText.indexOf(url);
int lastIndex = startIndex + url.length();
text.setSpan(new CustomTabsURLSpan(url), startIndex, lastIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return text;
}
return source;
}
@Override
public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction, Rect previouslyFocusedRect) {
}
}
3条答案
按热度按时间mwg9r5ms1#
这是因为
TextView
为每个链接文本模式创建URLSpan
,即ClickableSpan
。一旦MovementMethod
找到url,它就会调用URLSpan
的onClick
方法。此事件启动ACTION_VIEW
Intent,这就是为什么您会看到默认浏览器启动。您可以做的是编写自己的
URLSpan
实现,在其中覆盖onClick方法并从那里启动CustomTabs
服务。首先创建自定义
URLSpan
,它将覆盖onClick
方法:创建自定义转换方法,该方法将设置链接的跨度:
这里是快速解释:https://medium.com/@nullthemall/make-textview-open-links-in-customtabs-12fdcf4bb684#.ig1chpbbe
9cbw7uwe2#
我已经改变了尼古拉的答案,所以它仍然适用于其他linkify选项。
我添加了
Patterns.WEB_URL.matcher()
和一个构造函数来设置你想要的linkify选项。使用方法:
完整的类本身:
f45qwnt83#
下面是一个基于Nikola答案的Kotlin变体。我还在Chrome自定义选项卡中添加了URL处理: