在开发中,有时需要对文本之中的超链接或者类似于微博#话题#这样特殊文本进行过滤,包括特殊字符的点击事件,以及颜色处理,比如这样
这样的需求可以用原生的Linkify类来处理,下面是一个用来过滤http://或者https的链接写法,通过我们自己写的正则表达式来过滤超文本,然后原生的Linkify会给符合我们定义的规则(例如微博#话题#)改变颜色,并且点击可以特殊处理,与正常点击recyclerview或者lsitview条目跳转不同
/**
* 设置textview里面链接点击后跳转
*
* @param itemView 点击文字时,若点击区域不是链接,
默认是哪个view响应点击事件,通常情况就是listView或recyclerView的itemView
*/
public static void setURLClickEvent(final TextView tv, final View itemView) {
String text = tv.getText().toString();
if (!text.contains("http://") && !text.contains("https://") && !text.contains("ftp://") && !text.contains("$") && !text.contains("#")) {
tv.setMovementMethod(null);
return;
}
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setAutoLinkMask(0);
tv.setLinksClickable(true);
String scheme2 = String.format("%s/?%s=", "lcsdevdiv://sina_lcs_profile_", "uid");
tv.setLinkTextColor(FrameworkApp.getInstance().getResources().getColor(R.color.color_lcs_blue_pressed));
Pattern pattern2 =
Pattern.compile("((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)");
addLinks(tv, pattern2, scheme2, null, new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return URLEncoder.encode(url);
}
});
}
但是如何改变超文本的颜色呢?Textview已经提供了原生的方法
tv.setLinkTextColor(FrameworkApp.getInstance().getResources().getColor(R.color.color_lcs_blue_pressed));
但是如果挑剔的设计师想要去掉原生的下划线,怎么办,原生的Textview并没有提供修改下划线的方法
我们先去看看源码,在Linkify这个类中475行
private static final void applyLink(String url, int start, int end, Spannable text) {
URLSpan span = new URLSpan(url);
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
看到这个私有的添加链接的方法,然后找到找到URLSpan ,发现