一、在 textview中设置属性 android:autoLink="web"
二、重写urlspan类
看URLSpan所继承的类ClickableSpan类的源码,如下:
public abstract class ClickableSpan extends CharacterStyle implements UpdateAppearance {
/** * Performs the click action associated with this span. */ public abstract void onClick(View widget); /** * Makes the text underlined and in the link color. */ @Override public void updateDrawState(TextPaint ds) { ds.setColor(ds.linkColor); ds.setUnderlineText(true); } }
可以看到在这里它是重新设置为有下划线的。
所以要解决这个问题,就只有再设置一个没有下划线的Spannable对象。
首先,继承一个CharacterStyle或其已实现的子类,重写updateDrawState方法,代码如下:
public class NolineClickSpan extends URLSpan {
public NolineClickSpan(String url) {
super(url);
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false); // 设置没有下划线
}
}
三、将textview中内容替换
private void stripUnderlines(TextView textView) {
if (textView.getText() instanceof Spannable) {
Spannable s = (Spannable) textView.getText();
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); // 获取到所有的链接
for (URLSpan span : spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
NolineClickSpan mNoUnderlineSpan = new NolineClickSpan(
span.getURL());
s.setSpan(mNoUnderlineSpan, start, end, 0);
}
}
}
ok,这样就实现了无下划线的链接了!!!
demo下载地址:点击打开链接