標籤:height rri .net lsp style google 類型 連結 uri
布局檔案xml
1 <TextView2 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 @Override19 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 * 1388888888827 * www.google.com28 * [email protected]29 * jaycetest30 */
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 @Override46 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 }
來源: http://www.cnblogs.com/jayceli/archive/2012/09/03/2669475.html
來自為知筆記(Wiz)
Android TextView中連結(link)點擊事件的截取