Set different fonts inside TextView

I have two external fonts inside my project assets folder:

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

      

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

I can do it?

+3


source to share


1 answer


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

      



Using

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

      

+2


source







All Articles