TypefaceSpan

字体样式。可以设置不同的字体,比如系统自带的SANS_SERIFMONOSPACESERIF

构造函数:

  • TypefaceSpan(String family):参数family,字体的值,以字符串表示。
  • TypefaceSpan(Parcel src): 参数src,包含字体family信息的包装类。

示例1:

TypefaceSpan typefaceSpan = new TypefaceSpan("MONOSPACE");

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

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

示例2:

Parcel parcel = Parcel.obtain();
parcel.writeString("MONOSPACE");
parcel.setDataPosition(0);
TypefaceSpan typefaceSpan = new TypefaceSpan(parcel);

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

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

示例3:

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

TypefaceSpan typefaceSpan = new TypefaceSpan("MONOSPACE") {
    @Override
    public void updateDrawState(TextPaint textPaint) {
        textPaint.setColor(Color.argb(255, 54, 92, 124));
        textPaint.setUnderlineText(true);
    }
};

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

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