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); } }