StyleSpan

字体样式。可以设置正常、粗体、斜体和、加粗倾斜四种样式。

构造函数:

  • StyleSpan(int style):参数style,定义在Typeface中的常量。
  • StyleSpan(Parcel src):参数src,包含字体信息的包装类。

示例1:

StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(styleSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(spannableString);

示例2:

Parcel parcel = Parcel.obtain();
parcel.writeInt(Typeface.BOLD);
parcel.setDataPosition(0);
StyleSpan styleSpan = new StyleSpan(parcel);

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(styleSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(spannableString);

示例3:

重写updateDrawState(TextPaint textPaint)方法,修改字体的样式、文本颜色:

StyleSpan styleSpan = new StyleSpan(Typeface.BOLD) {
    @Override
    public void updateDrawState(TextPaint textPaint) {
        super.updateDrawState(textPaint);
        textPaint.setColor(Color.argb(255, 54, 92, 124));
    }
};

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(styleSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(spannableString);