Android ApiDemos示例解析(92):Text->Linkify

Linkify为TextView及其子类提供了将文字串自动转换为超链接的辅助类,当然文字串需要符合预定义或是自定义的正规表达式。

符合正规表达式(RegEx Pattern)文字串在转变为超链接后,当用户点击该超链接时,将会调用 startActivity(new Intent(Intent.ACTION_VIEW,uri) uri 为符合定义的文字串。

Linkify 允许使用任意的正规表达式来匹配文字,为方便起见,Android自带了几种正规表达式来匹配电话号码,Email,Http链接等。

Linkify 的静态方法addLinks

public static final boolean addLinks(TextView text, int mask)

  • text为一TextView对象
  • mask 可以为EMAIL_ADDRESSES,MAP_ADDRESSES,PHONE_NUMBERS,WEB_URLS等,表示可以匹配的系统自带的正规表达式类型。ALL表示全部类型

使用代码为TextView 添加超链接自动检测:

TextView textView=(TextView)findViewById(R.id.myTextView);
Linkify.addlinks(textView,Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES);

也可以在Layout中使用 TextView的android:autoLink属性来设置超链接类型,例如本例的TextView text1。

<TextView xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/text1″
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:autoLink=”all”
android:text=”@string/link_text_auto”
/>

Linkify也允许自定义RegEx的模式和匹配算法,本例没有介绍,详情可以参见http://developer.android.com/reference/android/text/util/Linkify.html

相关类有Pattern, MatchFilter等。

本例的text2 显示的String资源为

<b>text2:</b> This is some other
text, with a <a href=”http://www.google.com”>link</a> specified
via an &lt;a&gt; tag. Use a \”tel:\” URL
to <a href=”tel:4155551212″>dial a phone number</a>

这是一个HTML文字串,其中 a 为HTML的链接,在Android的TextView显示时也会显示为超链接,但缺省用户点击该链接时没有任何动作。需要使用setMovementMethod 为超链接添加点击时的操作LinkMovementMethod。

TextView t2 = (TextView) findViewById(R.id.text2);
t2.setMovementMethod(LinkMovementMethod.getInstance());

text3 和text2类似,只是不是从资源文件中显示文字而是通过代码来设置HTML文字

TextView t3 = (TextView) findViewById(R.id.text3);
t3.setText(
 Html.fromHtml(
 "<b>text3:</b>  Text with a " +
 "<a href=\"http://www.google.com\">link</a> " +
 "created in the Java source code using HTML."));
t3.setMovementMethod(LinkMovementMethod.getInstance());

text4 使用了SpannableString 类

SpannableString 定义一个只读字符串,但可以动态的为这个字符串的某个部分动态的添加和删除显示的格式。所支持的格式定义在包android.text.style中,包括对齐,缩放,等格式。

SpannableString ss = new SpannableString(
 "text4: Click here to dial the phone.");
 
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,
 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 
TextView t4 = (TextView) findViewById(R.id.text4);
t4.setText(ss);
t4.setMovementMethod(LinkMovementMethod.getInstance());

text4 显示的文字为text4: Click here to dial the phone.” ,然后通过setSpan将text4:格式改为粗体。here显示为超链接,链接的地址为一个电话号码。

public void setSpan(Object what, int start, int end, int flags)

  • what: 格式类型
  • start : 起始位置
  • end: 终止位置。
  • flags:标识位。



 


 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值