0

I have a custom font file, say myfont.ttf in assets/fonts/

I have created a custom View like this

public class IconFontView extends AppCompatTextView {
    public IconFontView(Context context) {
        super(context);
        applyIconFonts(context);
    }

    public IconFontView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        applyIconFonts(context);
    }

    public IconFontView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        applyIconFonts(context);
    }

    private void applyIconFonts(final Context context) {
        final Typeface iconFont = Typeface.createFromAsset(context.getAssets(), "fonts/myfont.ttf");
        setTypeface(iconFont);
    }
}

in XML:

<com.smule.singandroid.customviews.IconFontView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="400dp"
    android:text="@string/icontext"/> <!-- my unicode for the specific icon -->

strings.xml:

<string name="icontext">&#xe900;</string>

This way, I can see the preview perfectly fine. working preview

But, if I enter this fragment, I see nothing but an empty view. (using "Show layout bounds" to tell you that this view exists there, just not drawing) empty view

HOWEVER, if I add this font to my styles.xml like this

<style name="IconFont">
    <item name="fontPath">fonts/myfont.ttf</item>
</style>

and apply it in layout xml like this

<com.smule.singandroid.customviews.IconFontView
    style="@style/IconFont"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="400dp"
    android:text="@string/icontext"/> <!-- my unicode for the specific icon -->

This not only displays correct preview, but also shows the icon perfectly fine. working icon font

This has same effect as doing something like

mIconFontview.setText(R.string.icontext);
mIconFontView.setTypeFace(...);

Why would this work this way?

Then there would be no reason to create IconFontView at all. Might as well just use TextView.

Saehun Sean Oh
  • 2,103
  • 1
  • 21
  • 41
  • In support library 26 there's a new font feature. Check it out https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html – pantos27 Oct 27 '17 at 03:37
  • Sorry, my app must support from API 16, and at the moment I cannot upgrade support library in short time. – Saehun Sean Oh Oct 27 '17 at 04:38

0 Answers0