android textview支持多种格式跳转

时间:2024-01-01 20:22:45

http://www.linuxidc.com/Linux/2011-08/40530p2.htm

1.android:autoLink属性,使TextView中链接手机号码/网页/邮件/地图

android:autoLink的可选值为(none/web/email/phone/map/all) 设置一个URL链接 ,可以点击访问。

2.但是android:autoLink只认文字,对于设置文字连接的时候,可以用下面的方式

content.setText(Html
.fromHtml(
"企业注册入口:<a href=\"www.172sns.com\">rukou</a><br/><br/>"+
"企业微博:<a href=\"t.cn/z88bZ68\">http://t.cn/z88bZ68</a><br/><br/>"
+ "联系方式:4001 158 172"));
content.setMovementMethod(LinkMovementMethod.getInstance());
CharSequence text = content.getText();
if(text instanceof Spannable){
int end = text.length();
Spannable sp = (Spannable)content.getText();
URLSpan[] urls=sp.getSpans(0, end, URLSpan.class);
SpannableStringBuilder style=new SpannableStringBuilder(text);
style.clearSpans();//should clear old spans
for(URLSpan url : urls){
MyURLSpan myURLSpan = new MyURLSpan(url.getURL(),More.this);
style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
content.setText(style);
}
private static class MyURLSpan extends ClickableSpan{   

        private String mUrl;
private Context con;
MyURLSpan(String url,Context con) {
mUrl =url;
this.con = con;
}
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://"+mUrl));
con.startActivity(intent);
}
}