Android SpannableString: Style Text Easily

You can use SpannableString in Android to apply different styles to different parts of text, such as changing the color, size, and background. Here is a simple example code:

  1. Create a SpannableString object:
SpannableString spannableString = new SpannableString("Hello World");
  1. Set styles in SpannableString.
// 设置文字颜色
spannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// 设置文字大小
spannableString.setSpan(new AbsoluteSizeSpan(20, true), 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// 设置文字背景色
spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  1. Apply a SpannableString object to a TextView.
TextView textView = findViewById(R.id.text_view);
textView.setText(spannableString);

By using the code above, you can achieve rich text display effects by setting styles for specific parts of the text.

bannerAds