2016-03-28 197 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);