, , , ,

The ListViews in Android work on a combination of two things:

  1. Something that supplies the data – Adapter
  2. Something that supplies the view – getView() in the Adapter

Lets say there are 100 entries in a list and the screen size of the device can only show 15 of them at a time. Android does not create all 100 views, adding to a scrolling list, and show it to us. This causes unnecessary view inflations and hence slowing down the app. Instead, Android calls getView() only for the views that are shown — so only 15 in this case. When the user starts scrolling, the views that went out of the screen’s display are moved to a heap and new views are obtained through a call to getView(). When the user scrolls back to the initial set, Android tries to reuse the view it first created from the heap. This is what is passed as convertView to the getView() call. There are many blogs on perfecting the getView() using ViewHolder pattern.

When the Android moves the view to the heap, it gives us a chance to do anything with the view — like resetting the text in the view or removing images. Lets say the list we have is a list of images like in Instagram. Every time the user scrolls, more views are created and the older views are moved to heap. Even though the views are moved to heap, they still holds the huge ImageView’s drawable with them. This takes up so much memory. How can we avoid it? Lets make use of the chance that Android gives us.

theListView.setRecyclerListener(new RecyclerListener() {
    public void onMovedToScrapHeap(View view) {
        // Cast the view to the type of the view we inflated.
        MyCustomListRow row = (MyCustomListRow) view;

        // Get the view that holds the image and nullify the drawable.
        // GC will take care of cleaning up the memory used.