Listview内存使用情况

时间:2016-03-28 13:09:39

标签: java android listview memory android-viewholder

我有一个自定义列表视图,其中有一个用于显示数据的文本视图,我使用视图持有者模式来优化内存使用情况,但是当连续滚动列表视图时,内存分配上升(在Android工作室内的android监视器内存中) )

我该如何解决这个问题?

@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;
}

2 个答案:

答案 0 :(得分:2)

我认为这不是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;
    }
}

答案 1 :(得分:0)

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