privatevoidsetLinkClickable(finalSpannableStringBuilderclickableHtmlBuilder,finalURLSpanurlSpan){intstart=clickableHtmlBuilder.getSpanStart(urlSpan);intend=clickableHtmlBuilder.getSpanEnd(urlSpan);intflags=clickableHtmlBuilder.getSpanFlags(urlSpan);ClickableSpanclickableSpan=newClickableSpan(){publicvoidonClick(Viewview){//Do something with URL here.}};clickableHtmlBuilder.setSpan(clickableSpan,start,end,flags);}privateCharSequencegetClickableHtml(Stringhtml){SpannedspannedHtml=Html.fromHtml(html);SpannableStringBuilderclickableHtmlBuilder=newSpannableStringBuilder(spannedHtml);URLSpan[]urls=clickableHtmlBuilder.getSpans(0,spannedHtml.length(),URLSpan.class);for(finalURLSpanspan:urls){setLinkClickable(clickableHtmlBuilder,span);}returnclickableHtmlBuilder;}
如何使用
123456
TextViewmyTextView=(TextView)findViewById(R.id.myTextView);Stringurl="This is a page with lots of URLs. <a href=\"http://droidyue.com\">droidyue.com</> "+"This left is a very good blog. There are so many great blogs there. You can find what"+"you want in that blog."+"The Next Link is <a href=\"http://www.google.com.hk\">Google HK</a>";myTextView.setText(getClickableHtml(url));