Features of SpannableStringBuilderd
Extend the content in TextView, including adding pictures in TextView, controlling the size, color and background color of some text, and setting click events for any content of TextView, etc. The
sample code is as follows:
strText=findViewById(R.id.strText);
SpannableStringBuilder ssb=new SpannableStringBuilder("你好 ,安卓!");
//设置字体颜色
ForegroundColorSpan fcs=new ForegroundColorSpan(ContextCompat.getColor(this,R.color.colorPrimary));
ssb.setSpan(fcs,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
//设置背景颜色
BackgroundColorSpan bcs=new BackgroundColorSpan(ContextCompat.getColor(this,R.color.colorAccent));
ssb.setSpan(bcs,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
AbsoluteSizeSpan ass=new AbsoluteSizeSpan(80);
//设置字体大小
ssb.setSpan(ass,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
StyleSpan ss=new StyleSpan(Typeface.BOLD);
//设置字体类型
ssb.setSpan(ss,0,4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
ImageSpan is=new ImageSpan(this,R.mipmap.ic_launcher);
//添加图片
ssb.setSpan(is,4,6,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
//点击事件
ClickableSpan cs=new ClickableSpan() {
@Override
public void onClick(View view) {
Toaster.showShort(MainActivity.this,"你好,Grooter!");
}
};
ssb.setSpan(cs,4,6,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
strText.setText(ssb);
//为TextView添加链接
strText.setMovementMethod(LinkMovementMethod.getInstance());