Android TextView中連接(link)點擊事件的截取

佈局文件xmlhtml

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"就是連接全部類型的,包括網址,電話,郵件地址什麼的。android

Java代碼裏,對連接的事件進行監聽。app

 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 stub48                 /*
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 }




相關文章
相關標籤/搜索