【问题标题】:set different fonts inside TextView在 TextView 中设置不同的字体
【发布时间】:2015-07-22 11:00:08
【问题描述】:

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

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

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

我可以这样做吗?

【问题讨论】:

标签: android textview android-typeface


【解决方案1】:

为此,您需要使用自定义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 是可包裹的,但字体不是。 CustomTypefaceSpan需要实现parcelable接口,但是恢复Typeface对象是个问题。知道该怎么做吗?
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 2012-09-07
  • 2020-03-01
  • 2015-01-29
  • 2014-09-07
  • 2017-10-04
相关资源
最近更新 更多