Android中Textview超链接实现方式

2019-12-10 19:09:36王旭

现在就可以同时识别web以及自定义模式了。

同样的,这个超链接是默认颜色,如果需要改变颜色可以在xml中设置android:textColorLink="#1e84fb",或者在java代码中 设置tv.setLinkTextColor(color);

这时超链接还是带下划线的,如果想去掉,还是使用上面的思路,重写URLSpan,

public class Test10Activity extends Activity {
  TextView textView ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test10);
    textView = (TextView) findViewById(R.id.text);
    Pattern mentionsPattern = Pattern.compile("@(w+?)(?=W|$)(.)");
    String mentionsScheme = String.format("%s/?%s=", "mxn://profile", "uid");
    Linkify.addLinks(textView, Linkify.WEB_URLS);
    Linkify.addLinks(textView, mentionsPattern, mentionsScheme) ;
    stripUnderlines(textView) ;
  }
  private class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String url) {
      super(url);
    }
    @Override public void updateDrawState(TextPaint ds) {
      super.updateDrawState(ds);
      ds.setUnderlineText(false);
    }
  }
  private void stripUnderlines(TextView textView) {
    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);
      s.removeSpan(span);
      span = new URLSpanNoUnderline(span.getURL());
      s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
  }
}

Linkify还支持TranformFilter和MatchFilter接口。它们提供一些对目标URI的额外控制和定义匹配字符串,它们的使用如下的框架代码所示: Linkify.addLinks(myTextView, pattern, prefixWith, new MyMatchFilter(), new MyTransformFilter());

使用Match Filter

在你定义的MatchFilter中实现acceptMatch方法,来为RegEx样式匹配添加额外的条件。当一个潜在的匹配发现时,acceptMatch被触发, 匹配的开始点和结束点(包括被查找的整个文本)以参数的形式传入。接下来的代码显示了一个MatchFilter的实现,它取消任何之前已“.”结尾的匹配。

class MyMatchFilter implements MatchFilter {
     public boolean acceptMatch(CharSequence s, int start, int end) {
      return s.charAt(end-1) != '.';
     }
  }