listview内存使用情况

tzdcorbm  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(436)

我有一个自定义列表视图,它有一个文本视图来显示数据,我使用视图持有者模式来优化内存使用,但是当连续滚动列表视图时,内存分配会增加(在android studio中的android monitor内存中)
我该如何解决这个问题?

@Override
public View getView(int position, View view, ViewGroup parent) {

    ViewContainer viewContainer;
    View rowView = view;

    if(rowView==null){

        LayoutInflater inflater = context.getLayoutInflater();
        rowView= inflater.inflate(R.layout.lv2rowlayout, null, true);

        viewContainer = new ViewContainer();
        //---get a reference to all the views on the xml layout---

        viewContainer.txten = (TextView) rowView.findViewById(R.id.txten);
        viewContainer.txtfars = (TextView) rowView.findViewById(R.id.txtfars);

        String s ;
        Typeface custom_font;

        viewContainer.txten.setTextSize(TypedValue.COMPLEX_UNIT_SP,sd.enSize);
        s="fonts/"+sd.enFont;
        custom_font = Typeface.createFromAsset(context.getAssets(),s );
        viewContainer.txten.setTypeface(custom_font);
        viewContainer.txten.setTextColor(sd.enColor);

        viewContainer.txtfars.setTextSize(TypedValue.COMPLEX_UNIT_SP,sd.farssize);
        s="fonts/"+sd.farsFont;
        custom_font = Typeface.createFromAsset(context.getAssets(),s );
        viewContainer.txtfars.setTypeface(custom_font);
        viewContainer.txtfars.setTextColor(sd.farsColor);

        rowView.setTag(viewContainer);
    }
    else {
        viewContainer = (ViewContainer) rowView.getTag();

    }

    //---customize the content of each row based on position---
    viewContainer. txten.setText(en[position]);
    viewContainer.txtfars.setText(fars[position]);

    return rowView;
}
icnyk63a

icnyk63a1#

我想不是因为 ListView ,是关于 Typeface.createFromAsset(...) 这是一个众所周知的问题(https://code.google.com/p/android/issues/detail?id=9904)这可能会导致某些设备出现内存泄漏。您可以这样缓存字体创建:

public class FontCache {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();

    public static Typeface get(String name, Context context) {
        Typeface tf = fontCache.get(name);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(context.getAssets(), name);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(name, tf);
        }
        return tf;
    }
}
hl0ma9xz

hl0ma9xz2#

尝试设置如下代码段所示 custom_font = Typeface.createFromAsset(context.getAssets(),s ); 在适配器的构造函数中。

相关问题