TextView是用來顯示文本的,有時需要給TextView中的個别字設定為超連結,或者設定個别字的顔色、字型等,那就需要用到Spannable對象,可以借助Spannable對象實作以上設定。
Activity代碼:
package com.zhou.activity;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.widget.TextView;
public class TextViewLinkActivity extends Activity {
TextView myTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myTextView = (TextView) this.findViewById(R.id.myTextView);
//建立一個 SpannableString對象
SpannableString sp = new SpannableString("這句話中有百度超連結,有高亮顯示,這樣,或者這樣,還有斜體.");
//設定超連結
sp.setSpan(new URLSpan("http://www.baidu.com"), 5, 7,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//設定高亮樣式一
sp.setSpan(new BackgroundColorSpan(Color.RED), 17 ,19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//設定高亮樣式二
sp.setSpan(new ForegroundColorSpan(Color.YELLOW),20,24,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//設定斜體
sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 27, 29, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//SpannableString對象設定給TextView
myTextView.setText(sp);
//設定TextView可點選
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
}