Listview memory leak

后端 未结 2 1488
抹茶落季
抹茶落季 2021-01-01 08:28

I have a simple list view with adapter. I create 10+ listviewitems dynamically. Then I scroll up and down again and again and again.... I can see that available memory keeps

相关标签:
2条回答
  • 2021-01-01 08:37

    I'm not sure if it is correct to classify this as a bug, but every time you use Typeface.createFromAsset if creates a new font asset and does not release it. See this.

    What you can do is load the typefaces when you load your app and reference them statically. I put my typefaces in Application.

    public class YourApp extends android.app.Application {
        public void onCreate() {
            super.onCreate();
    
            // typeface caching
            initializeTypefaces();
        }
    
        public static class Fonts {
            public static Typeface THEOREM;
        }
    
        private void initializeTypefaces(){
            Fonts.THEOREM   = Typeface.createFromAsset(getAssets(), "fonts/theorem.otf");
        }
    }
    

    And then I do this in my adapter:

    textView.setTypeface(YourApp.Fonts.THEOREM);
    

    You can go here to see how to use Application in Android.

    Lastly, it looks like your still creating your ViewHolder every time instead of only when convertView is null. I would review this video to get the whole picture. http://www.google.com/events/io/2010/sessions/world-of-listview-android.html

    Here is an example of how I use the ViewHolder method:

    @Override
    public View getView(int pos, View convertView, ViewGroup parent) {
        ViewHolder holder;
    
        if(convertView == null || convertView.getTag() == null){
            convertView = inflater.inflate(R.layout.list_item, parent, false);
            holder = new ViewHolder();
    
            holder.text1  = (TextView)convertView.findViewById(R.id.list_item_text1);
            holder.text2  = (TextView)convertView.findViewById(R.id.list_item_text2);
            holder.text1.setTypeface(YourApp.Fonts.THEOREM); // only happens once when recycling!
    
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
    
        holder.text1.setText("someText");
        holder.text2.setText("someText");
        return convertView;
    }
    
    0 讨论(0)
  • 2021-01-01 08:51

    You can try to free the resources if convertView != null. if it is you could find your Views and null them. You could also try to get the Bitmap of your ImageView and recycle it. you could also add your ViewHolder as a member to your RecipeInstructionsListViewAdapter and instantiate it once in constructor.

    0 讨论(0)
提交回复
热议问题