Android TextView中链接(link)点击事件的截取

布局文件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代码里,对链接的事件进行监听。

package com.jayce.testlink;
 
 import android.net.Uri;
 import android.os.Bundle;
 import android.app.Activity;
 import android.content.Intent;
 import android.text.Spannable;
 import android.text.SpannableStringBuilder;
 import android.text.style.ClickableSpan;
 import android.text.style.URLSpan;
 import android.util.Log;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.TextView;
 
 public class TextLinkActivity extends Activity {
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_text_link);
         TextView tv = (TextView)findViewById(R.id.test_note);
         CharSequence text = tv.getText(); 
         /*
          * 以下是textview的内容(这里给了3个示例链接和一个普通字符串)
          * 13888888888
          * www.google.com
          * [email protected]
          * jaycetest
          */
         if (text instanceof Spannable) {  
             int end = text.length();
             Spannable sp = (Spannable) tv.getText();  
             URLSpan[] spans = sp.getSpans(0, end, URLSpan.class);  
             SpannableStringBuilder style = new SpannableStringBuilder(text);  
             style.clearSpans();// should clear old spans  
             for (URLSpan span : spans) {  
                 JayceSpan mySpan = new JayceSpan(span.getURL());  
                 style.setSpan(mySpan, sp.getSpanStart(span), sp.getSpanEnd(span), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);  
             }  
             tv.setText(style); 
         }
         tv.setOnClickListener(new OnClickListener(){
 
             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                 /*
                  * 这里是对所有点击消息的监听
                  * 可以把链接的做标记剔除后监听非链接的点击
                  * 比如jaycetest区域的点击
                  */
             }});
     }
     
     private  class JayceSpan extends ClickableSpan {  
           
         private String mSpan;  
   
         JayceSpan(String span) {  
             mSpan = span;  
         }  
   
         @Override  
         public void onClick(View widget) {  
             Log.e("jayce", "span:" + mSpan);
             /*链接被点击
              * 这里可以做一些自己定义的操作
              */
             Intent intent = new Intent(Intent.ACTION_VIEW);
             intent.setData(Uri.parse(mSpan));
             startActivity(intent);
         }  
     }  
 
 }

 

你可能感兴趣的:(textview)