问题
To display & load images in my ListView I've created a custom ArrayAdapter, however it is really slow. Every time I scroll through the list it loads the images again.
Is there a caching mechanism which will cache my Views so I don't need to refill them every time? I know about the ViewHolder method, however this still is slow or am I just using it wrong?
My code:
public class ImageArrayAdapter extends ArrayAdapter<HashMap<String, String>> {
private int resourceId = 0;
private LayoutInflater inflater;
public ImageArrayAdapter(Context context, int resource,
List<HashMap<String, String>> objects) {
super(context, 0, objects);
this.resourceId = resource;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
public TextView title;
public TextView text;
public WebImageView image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
view = inflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.item_text);
holder.image = (WebImageView) view.findViewById(R.id.item_image);
holder.title = (TextView) view.findViewById(R.id.item_title);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
HashMap<String, String> item = (HashMap<String, String>) getItem(position);
holder.text.setText(item.get("text"));
holder.title.setText(item.get("title"));
holder.image.setImageUrl(item.get("image"));
holder.image.loadImage();
return view;
}
}
回答1:
You can store your Bitmaps in a LRU (Least Recently Used) cache based on SoftReferences.
That kind of cache keeps your most used objects in memory, and when the systems comes out of memory the usage of SoftReference allow the GarbageCollector to free these resources.
Here is an implementation I am currently using in my app EmailAlbum: http://code.google.com/p/emailalbum/source/browse/EmailAlbumAndroid/tags/REL-2_9_3/src/com/kg/emailalbum/mobile/util/NewLRUCache.java
This was taken from this French post about java cache implementations, I just renamed a few methods to allow switching from Hashmap to this cache without having to modify method calls.
Then, you will certainly want to avoid the UI from slowing down each time a picture is beeing read from SDCard (or the web). That's when you will have to look to AsyncTask which allows to loa pictures in a background Thread while letting the user interact with the UI (like scroll faster even when pictures are beeing loaded).
来源:https://stackoverflow.com/questions/3949041/android-arrayadapter-listview-slowness