Using Custom Fonts Properly in Android

房东的猫 提交于 2020-01-01 12:05:08

问题


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



来源:https://stackoverflow.com/questions/22642275/using-custom-fonts-properly-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!