android---TextView中电话号码、网址自动链接的实现方法

来源:互联网 发布:win7 找不到网络打印机 编辑:程序博客网 时间:2024/06/05 23:51

出自:http://www.cnblogs.com/jico/archive/2010/11/02/1867437.html

假若TextView文本中有电话号码或者网址,我想通过点击电话号码或者网址就能实现打电话或者打开网页,android中已经为我们提供这样的属性和方法进行设置,大体可以分为三种:

1、设置TextView的autoLink属性:他有几个值all、web、phone、email等。当文中有这几种类型的文本值时,点击它将进入网页、打电话或者email的activity,这是最简单的方法

2、在文本值直接添加链接

    (1)例如在string.xml文件中:<string><a href=http://www.google.com>http://www.google.com</a> <a href="tel:18600000001">tel</a> </string>,同时设置TextView属性setMovementMethod(LinkMovementMethod.getInstance());

    (2)在代码中使用Hteml.fromHtml构建文本

复制代码
代码
tv2.setText(
Html.fromHtml(
"the google url: " +
"<a href=\"http://www.google.com\">http://www.google.com</a><br/>" +
"the telephone: " +
"<a href=\"tel:18603045201\">18603045201</a>)"
));
tv2.setMovementMethod(LinkMovementMethod.getInstance());
复制代码

3、使用SpanableString指定某段字串为链接文本

 

复制代码
代码
TextView tv3=(TextView)findViewById(R.id.tv3);
SpannableString ss
=
new SpannableString("the google url: http://www.google.com 18600000001");
ss.setSpan(
new URLSpan("http://www.google.com"),
16, 37, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(
new URLSpan("tel:18603045201"),
38, 49, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv3.setText(ss);
tv3.setMovementMethod(LinkMovementMethod.getInstance());
复制代码

1 0
原创粉丝点击