public class AndrodTActivity extends Activity implements OnClickListener {
TextView tv_;
TextView tv1; android
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 點擊tv1時,讓其跳轉到咱們自定義的位置 使用android.text.style.ClickableSpan類能夠自定義單擊URL鏈接的動做。
tv_ = (TextView) findViewById(R.id.tv_);
String text = tv_.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "hello activity", Toast.LENGTH_SHORT).show();
}
}, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// 使用SpannabelString對象設置TextView組件內容
tv_.setText(span);
tv_.setMovementMethod(LinkMovementMethod.getInstance()); ide
// TextView中的個別字設置爲超連接,或者設置個別字的顏色、字體等
tv1 = (TextView) findViewById(R.id.tv1);
SpannableString sp = new SpannableString("這句話中有百度超連接,有高亮顯示,這樣,或者這樣,還有斜體.");
// 設置超鏈接
URLSpan urlSpan = new URLSpan("http://www.baidu.com");
sp.setSpan(urlSpan, 5, 7, Spannable.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);
// 將sp設置給TextView
tv1.setText(sp);
tv1.setMovementMethod(LinkMovementMethod.getInstance());
} 字體
@Override
public void onClick(View v) { this
} url
} spa
同時設置文本的顏色與背景色 能夠寫個通用的類 對象
代碼: get
public class ColorSpan extends CharacterStyle {
private int mTextColor;
private int mBackgroundColor; it
public ColorSpan(int mTextColor, int mBackgroundColor) {
super();
this.mTextColor = mTextColor;
this.mBackgroundColor = mBackgroundColor;
} io
@Override public void updateDrawState(TextPaint tp) { tp.bgColor = mBackgroundColor; tp.setColor(mTextColor); } }