在TextView中设置不同的字体

时间:2015-07-22 11:00:09

标签: android textview android-typeface

我项目的资产文件夹中有两个外部字体:

Typeface font1 = Typeface.createFromAsset(getActivity().getAssets(),"fonts/firstFont.otf");
Typeface font2 = Typeface.createFromAsset(getActivity().getAssets(),"fonts/secondFont.otf");

现在我将使用这两种不同的字体格式化textview中的文本。例如,如果TextView包含"您好,我是textview内容",我会将font1应用于"您好,"和" textview"和font2到"我' m"和"内容"。

我能做到吗?

1 个答案:

答案 0 :(得分:2)

为此,您需要使用自定义TypefaceSpan

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);
}
}

<强>用法

        TextView txt = (TextView) findViewById(R.id.custom_fonts);  

        Typeface font1 = Typeface.createFromAsset(getActivity().getAssets(),"fonts/firstFont.otf");
        Typeface font2 = Typeface.createFromAsset(getActivity().getAssets(),"fonts/secondFont.otf");

        SpannableStringBuilder spanString = new SpannableStringBuilder("Hello, i'm textview content");

        spanString.setSpan(new CustomTypefaceSpan("", font1), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        spanString.setSpan(new CustomTypefaceSpan("", font), 4, 26,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        txt.setText(spanString);