How to use SpannableString in Android?
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:
- Create a SpannableString object:
SpannableString spannableString = new SpannableString("Hello World");
- 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);
- 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.