Using Custom Fonts Properly in Android

2019-04-10 00:23发布

问题:

So I've extended TextView to use a custom font (as described here), i.e.,

public class CustomTextView extends TextView {
    public static final int CUSTOM_TEXT_NORMAL = 1;
    public static final int CUSTOM_TEXT_BOLD = 2;

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCustomTextView(context, attrs);
    }

    private void initCustomTextView(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);
        int typeface = array.getInt(R.styleable.CustomTextView_typeface, CUSTOM_TEXT_NORMAL);
        array.recycle();
        setCustomTypeface(typeface);
    }

    public setCustomTypeface(int typeface) {
         switch(typeface) {
             case CUSTOM_TEXT_NORMAL:
                 Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextNormal.ttf");
                 setTypeface(tf);
                 break;
             case CUSTOM_TEXT_BOLD: 
                 Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextBold.ttf");
                 setTypeface(tf); 
                 break;
         }
     } 
}

I then use CustomTextView in a fragment added to activity's main layout. All works fine, but there appears to be some memory issues, i.e., every time I rotate the screen (causing the activity to go through its life cycle), the font assets are loaded into the native heap in addition to the previous load. For example; below is a screen dump from adb shell dumpsys meminfo my.package.com after the initial load and no screen rotations (using Roboto-Light font):

and the same screen dump after a few rotaions

What is clear is the increase in the Asset Allocations and the Native Heap that occurs on each screen rotation (GC doesn't clear this up either). Surely then we shouldn't be using custom fonts in the manner described above and, if not, how should we be using custom fonts?

回答1:

You should find your answer here.

Basically you need to build your own system to cache those typefaces after you create them (and therefore you'll only be creating each typeface once).