JayceLi  

布局文件xml

1 <TextView
2                 android:layout_width="match_parent"
3                 android:layout_height="match_parent"
4                 android:id="@+id/test_note"
5                 android:autoLink="all"
6                 />

这里autoLink="all"就是链接所有类型的,包括网址,电话,邮件地址什么的。

Java代码里,对链接的事件进行监听。

 1 package com.jayce.testlink;
 2 
 3 import android.net.Uri;
 4 import android.os.Bundle;
 5 import android.app.Activity;
 6 import android.content.Intent;
 7 import android.text.Spannable;
 8 import android.text.SpannableStringBuilder;
 9 import android.text.style.ClickableSpan;
10 import android.text.style.URLSpan;
11 import android.util.Log;
12 import android.view.View;
13 import android.view.View.OnClickListener;
14 import android.widget.TextView;
15 
16 public class TextLinkActivity extends Activity {
17 
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_text_link);
22         TextView tv = (TextView)findViewById(R.id.test_note);
23         CharSequence text = tv.getText(); 
24         /*
25          * 以下是textview的内容(这里给了3个示例链接和一个普通字符串)
26          * 13888888888
27          * www.google.com
28          * test@gmail.com
29          * jaycetest
30          */
31         if (text instanceof Spannable) {  
32             int end = text.length();
33             Spannable sp = (Spannable) tv.getText();  
34             URLSpan[] spans = sp.getSpans(0, end, URLSpan.class);  
35             SpannableStringBuilder style = new SpannableStringBuilder(text);  
36             style.clearSpans();// should clear old spans  
37             for (URLSpan span : spans) {  
38                 JayceSpan mySpan = new JayceSpan(span.getURL());  
39                 style.setSpan(mySpan, sp.getSpanStart(span), sp.getSpanEnd(span), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);  
40             }  
41             tv.setText(style); 
42         }
43         tv.setOnClickListener(new OnClickListener(){
44 
45             @Override
46             public void onClick(View v) {
47                 // TODO Auto-generated method stub
48                 /*
49                  * 这里是对所有点击消息的监听
50                  * 可以把链接的做标记剔除后监听非链接的点击
51                  * 比如jaycetest区域的点击
52                  */
53             }});
54     }
55     
56     private  class JayceSpan extends ClickableSpan {  
57           
58         private String mSpan;  
59   
60         JayceSpan(String span) {  
61             mSpan = span;  
62         }  
63   
64         @Override  
65         public void onClick(View widget) {  
66             Log.e("jayce", "span:" + mSpan);
67             /*链接被点击
68              * 这里可以做一些自己定义的操作
69              */
70             Intent intent = new Intent(Intent.ACTION_VIEW);
71             intent.setData(Uri.parse(mSpan));
72             startActivity(intent);
73         }  
74     }  
75 
76 }
posted on 2012-09-03 21:36  JayceLi  阅读(4346)  评论(3编辑  收藏  举报