0

ListViews ask Adapters for Views before they can be seen on screen. The default implementation of an Adapter actually inflates your views when the ListView asks for them.

When using an Object extends ArrayAdapter<MyObject>, we could actually store all the views in a HashMap<MyObject, SoftReference<View>> and override ArrayAdapter.getView so we can inflate our Views only once, but if the GarbageCollector passes and makes our Views null (or my SoftReferences are made null for any strange reason) we inflate them again.

@Override
public View getView(final int position, final View convertView,
        final ViewGroup parent)
{
    final MyObject mo = getItem(position);
    if (hashMap.get(mo) == null || hashMap.get(mo).get() == null)
    {
        final MyCustomView mcv = new MyCustomView(getContext());
        hashMap.put(mo, new SoftReference<MyObject>(mcv));
    } 
    return hashMap.get(mo).get();
}

I've tried it and it works fine and nice. Is this implementation disencouraged in any way?

1 Answer 1

1

we could actually store all the views

You should use ViewHolder pattern. It allows you not to create all the views, but only those you need to display on the screen at the moment.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually, with the ViewHolders you only need to inflate views once, because it's a static class. Calling findViewById() is very demanding.
This approach creates the views as the ListView demands them, but creates them only once. Isn't it the same?
@santirivera92 The thing is to inflate views only once. Then you should reuse views. If only 6 listview items can be shown on the screen at a time, you don't need 100 listview items. You only need 6.
Where are those views that are not being shown but have been inflated stored?
The point is, you don't have views which are not used. You have the exact number of views: if screen can show only 6 views in list at a time, you have 6 views. And then you REUSE them. You separate the representation and data, so you store data in List or Set(which is a field of your Adapter object).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.