Charlie-Blake
Charlie-Blake

Reputation: 11050

Adapter implementation with HashMap

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?

Upvotes: 0

Views: 99

Answers (1)

user468311
user468311

Reputation:

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.

Upvotes: 1

Related Questions