首先看一个链接文本执行流程的大概示意图
看了这个流程应该对大概URL, Email等的链接实现有所了解了,所以直接看代码把
TextView view1 = (TextView) findViewById( R.id.view1 ); TextView view2 = (TextView) findViewById( R.id.view2 ); TextView view3 = (TextView) findViewById( R.id.view3 ); TextView view4 = (TextView) findViewById( R.id.view4 ); TextView view5 = (TextView) findViewById( R.id.view5 ); TextView view6 = (TextView) findViewById( R.id.view6 ); SpannableString text1 = new SpannableString("red"); text1.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view1.setText( text1 ); SpannableString text2 = new SpannableString("green"); text2.setSpan(new BackgroundColorSpan(Color.GREEN), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view2.setText( text2 ); SpannableString text3 = new SpannableString("i am bold"); text3.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view3.setText( text3 ); SpannableString text4 = new SpannableString("underline"); text4.setSpan(new UnderlineSpan(), 0, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view4.setText( text4 ); SpannableString text5 = new SpannableString("delete line"); text5.setSpan(new StrikethroughSpan(), 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view5.setText( text5 ); SpannableString text6 = new SpannableString("make a call"); text6.setSpan(new URLSpan("tel:123456789"), 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view6.setText( text6 ); view6.setMovementMethod(LinkMovementMethod.getInstance()); // 还有ImageSpan等
XML布局文件
默认的链接在点击时,只会跳转到响应的View,如点击URL时,打开浏览器,点击电话号码时,打开拨号界面。 如果我们要在点击某连接时,跳转到某个Activity呢。
URLSpan继承自ClickableSpan,所以我们的出发点也是这个类,然后重写其中的onClick
public class IntentSpan extends ClickableSpan implements ParcelableSpan { private Intent mIntent; public IntentSpan(Intent toActivity) { mIntent = toActivity; } @Override public void onClick(View sourceView) { Context context = sourceView.getContext(); context.startActivity( mIntent ); } @Override public int getSpanTypeId() { return 100; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flag) { // don't write to parcel } public Intent getIntent() { return mIntent; } }
使用的话和URLSpan差不多
SpannableString text6 = new SpannableString("make a call"); Intent intent = new Intent(context, SomActivity.class); text6.setSpan(new IntentSpan(intent), 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); view6.setText( text6 ); view6.setMovementMethod(LinkMovementMethod.getInstance());