按這一篇(http://www.linuxidc.com/Linux/2011-10/45649.htm)的方式可以給 TextView 加上事件響應,然而僅限於 web、email、phone、map等幾種,如果希望在點擊後跳轉到自己的 Activity 要怎麼實現呢?看代碼吧!
這是 Activity 代碼:
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- linkify = new LinkifyUtil(this);
- Intent intent = new Intent("com.example.Android.note.ADD");
- intent.setData(Uri.parse("content://com.example.android.note/item"));
-
- linkify.addIntentLink(intent, (TextView) findViewById(R.id.tv_new_item));
- }
這是 LinkifyUtil 類:
- package com.example.android.note.util;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.text.SpannableString;
- import android.text.Spanned;
- import android.text.method.LinkMovementMethod;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.TextView;
-
- /**
- *
- * @author eidolon
- */
- public class LinkifyUtil {
- private final Activity currentActivity;
-
- public LinkifyUtil(Activity activity) {
- this.currentActivity = activity;
- }
-
- public void addIntentLink(final Intent intent, final TextView view, final int start, final int end) {
- CharSequence source = view.getText();
- if (source instanceof Spanned) {
- IntentSpan[] spans = ((Spanned) source).getSpans(start, end, IntentSpan.class);
- if (spans.length > 0) {
- return;
- }
- }
-
- SpannableString spannableString = new SpannableString(source);
- spannableString.setSpan(new IntentSpan(new OnClickListener() {
-
- public void onClick(View view) {
- currentActivity.startActivity(intent);
- }
- }), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- view.setText(spannableString);
- view.setMovementMethod(LinkMovementMethod.getInstance());
- }
-
- public void addIntentLink(final Intent intent, final TextView view) {
- addIntentLink(intent, view, 0, view.getText().toString().length());
- }
- }
最後是 IntentSpan 類:
- package com.example.android.note.util;
-
- import android.text.style.ClickableSpan;
- import android.view.View;
- import android.view.View.OnClickListener;
-
- /**
- *
- * @author eidolon
- */
- public class IntentSpan extends ClickableSpan {
-
- private final OnClickListener listener;
-
- public IntentSpan(View.OnClickListener listener) {
- this.listener = listener;
- }
-
- @Override
- public void onClick(View view) {
- listener.onClick(view);
- }
- }