public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str="32号字体加粗斜体加粗斜体红色绿色背景";
SpannableStringBuilder style=new SpannableStringBuilder(str);
style.setSpan(new AbsoluteSizeSpan(sp2px(this,32)), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new StyleSpan(Typeface.BOLD),5,7,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new StyleSpan(Typeface.ITALIC),7,9,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new StyleSpan(Typeface.BOLD_ITALIC),9,13,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.RED),13,15,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
style.setSpan(new BackgroundColorSpan(Color.GREEN),15,19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView=(TextView) findViewById(R.id.text);
textView.setText(style);
}
public static int sp2px(Context context, float spValue){
final float scale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * scale + 0.5f);
}
}