2016-03-28 161 views
1

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

我应该如何解决这个问题?

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

由于你的字体不依赖于位置,为什么你不声明一个全局变量并在列表视图的构造函数中初始化它? – Kaustuv

+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; 
    } 
} 
+0

而不是如果这样:'s =“fonts /”+ sd.enFont; custom_font = Typeface.createFromAsset(context.getAssets(),s); viewContainer.txten.setTypeface(custom_font);' 你用这个设置字体:'s =“fonts /”+ sd.enFont; viewContainer.txten.setTypeface(FontCache.get(s,context));' – GaborNovak

0

尝试在适配器的构造下面摘​​录 custom_font = Typeface.createFromAsset(context.getAssets(),s);