在TextView内设置不同的字体

3

我在项目的assets文件夹中有两种外部字体:

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

现在,我需要在TextView中应用两种不同的字体格式来格式化文本。例如,如果TextView包含 “Hello, i'm textview content”,我想将font1应用于“Hello,”和“textview”,将font2应用于“i'm”和“content”。

我该怎么做?


我不确定,但可以看一下这个链接:https://dev59.com/xGkw5IYBdhLWcg3w1d8m - M D
看这里:https://dev59.com/sGQo5IYBdhLWcg3wE8C2 虽然不完全相同,但足够接近。 - Didi78
1个回答

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

TypefaceSpan可以被序列化,但Typeface不能。CustomTypefaceSpan需要实现Parcelable接口,但是恢复Typeface对象是个问题。有什么好主意吗? - AndrewBloom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接