3

I have two external fonts inside assets folder of my project:

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

Now i would format a text inside a textview with this two different font. For example, if TextView contains "Hello, i'm textview content", i would apply font1 to "Hello," and "textview" and font2 to "i'm" and "content".

I can i do that?

giozh
  • 9,868
  • 30
  • 102
  • 183
  • I am not sure but take a look [http://stackoverflow.com/questions/9618835/apply-two-different-font-styles-to-a-textview](http://stackoverflow.com/questions/9618835/apply-two-different-font-styles-to-a-textview) – M D Jul 22 '15 at 11:02
  • take a look here: http://stackoverflow.com/questions/16335178/different-size-of-strings-in-the-same-textview not the same, but close enaugh – Didi78 Jul 22 '15 at 11:03

1 Answers1

2

For this you need to use a custom 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);
}
}

Usage

        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);
Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
  • TypefaceSpan is parcelable but Typeface is not. CustomTypefaceSpan needs to implement the parcelable interface, but it's a problem restore the Typeface object. Any idea how to do that? – AndrewBloom Mar 09 '17 at 17:02