android TextView中识别多个url并分别点击跳转方法详解
实现方案:
我们直接参考实例代码:
privateStringpattern= "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?|(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?"; Patternr=Pattern.compile(pattern); Matcherm; mTv.setText(identifyUrl(richURL.msg)); publicSpannableStringBuilderForAllversidentifyUrl(CharSequencetext){ CharSequencecontextText; CharSequenceclickText; text=text==null?"":text; //以下用于拼接本来存在的spanText SpannableStringBuilderForAllversspan=newSpannableStringBuilderForAllvers(text); ClickableSpan[]clickableSpans=span.getSpans(0,text.length(),ClickableSpan.class); if(clickableSpans.length>0){ intstart=0; intend=0; for(inti=0;i=getText().length()){ intoff1=layout.getOffsetForHorizontal(line,x-getTextSize()); if(off==off1){ returnhandled; } } ClickableSpan[]links=spannable.getSpans(off,off,ClickableSpan.class); if(links.length>0){ ClickableSpanclickableSpan=links[0]; intstart=spannable.getSpanStart(clickableSpan); intend=spannable.getSpanEnd(clickableSpan); if(action==MotionEvent.ACTION_DOWN&&!hasSpan){ spannable.setSpan(backgroundColorSpan,start,end,Spanned.SPAN_INCLUSIVE_INCLUSIVE); hasSpan=true; }elseif(hasSpan){ spannable.removeSpan(backgroundColorSpan); hasSpan=false; } } returnlinks.length!=0; }else{ if(hasSpan&&action!=MotionEvent.ACTION_MOVE){ spannable.removeSpan(backgroundColorSpan); hasSpan=false; } } returnhandled; } }
以上实例代码大家可以测试下,感谢大家的学习和对毛票票的支持。