按上一篇的方式可以给 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); } }?
?