2

I have a TextView and I need to display the following string on it: "Some text". And I want the TextView to use a custom font for this. So I need to get the following output: enter image description here

I tried the following code:

    textView.setText("some <i>text</i>");
    final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
    if (typeface != null)
        textView.setTypeface(typeface);

But the result was: enter image description here, so the Italic is actually fake, generated by the system. Then I tried the following:

    textView.setText("some <i>text</i>");
    final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
    if (typeface != null)
        textView.setTypeface(typeface, Typeface.NORMAL);
    final Typeface typefaceItalic = Typeface.createFromAsset(getActivity().getAssets(), "customfont-italic.otf");
    if (typefaceItalic != null)
        textView.setTypeface(typefaceItalic, Typeface.ITALIC);

But the output was all-italic! enter image description here

So how can I combine custom typefaces for regular and italic in a single TextView?

netimen
  • 4,199
  • 6
  • 41
  • 65

1 Answers1

0

After some research I found the following solution for this:

    final Typeface typefaceItalic = Typeface.createFromAsset(getActivity().getAssets(), "customfont-italic.otf");

    // there is no easy way in Android to make a single TextView display text using custom typeface with different styles (regular and italic). We need to replace all Italic spans with custom typeface spans for this.
    final SpannableString text = new SpannableString("some <i>text</i>");
    final StyleSpan[] spans = text.getSpans(0, text.length(), StyleSpan.class);
    for (StyleSpan span : spans) {
        if (span.getStyle() == Typeface.ITALIC) {
            text.setSpan(new CustomTypefaceSpan("customfont", italicTypeface), text.getSpanStart(span), text.getSpanEnd(span), 0);
            text.removeSpan(span);
        }
    }
    textView.setText(text);

    final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
    if (typeface != null)
        textView.setTypeface(typeface, Typeface.NORMAL);

CustomTypefaceSpan is a class described here: https://stackoverflow.com/a/4826885/190148

Community
  • 1
  • 1
netimen
  • 4,199
  • 6
  • 41
  • 65