我正在尝试使TypefaceSpan TypefaceSpan on developer.android.com

该页面上提供的示例使用新的TypefaceSpan(Typeface)似乎现在是错误的,因为没有这样的构造函数。因此,我尝试使用新的TypefaceSpan(Parcel)时没有运气(我不知道如何正确地将Typeface放入Parcel),而新的TypefaceSpan(String)仅支持系统字体(我无法使其与自定义字体一起使用) 。

有谁知道,如何将TypefaceSpan与自定义字体一起使用(来自res / font)?

最佳答案

希望这对您有用。

像这样声明变量:

  Typeface typeface;


像这样初始化变量:

 typeface = Typeface.createFromAsset(getAssets(), "fonts/yourFontName.ttf");


设置为这样的视图:

 yourView.setTypeface(typeface);


上面的代码用于将字体设置为视图。

对于CustomTypeFaceSpan,将以下类添加到您的包中。

public class CustomTypefaceSpan extends TypefaceSpan {

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }
}


像这样使用上面的类:

     Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/YourFontName.ttf");
     SpannableString mNewTitle = new SpannableString("Your String Value");
     mNewTitle.setSpan(new CustomTypefaceSpan("", typeface), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
     yourView.setText(mNewTitle);

10-07 16:45