How could I change an image inside of a ListView?
I read another posts and I did not find a solution for me. I created a custom ListView. Each and every item of the this list is complex-item, containing ImageView plus two TextViews. After the adapter is applied and the list is filled up, I want to change the image inside the ImageView, but I want that to happen not on click event.
private class ListAdapter extends ArrayAdapter<RSSItem> {
private List<RSSItem> items;
public ListAdapter(Context context, int textViewResourceId, List<RSSItem> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
开发者_Python百科 v = vi.inflate(R.layout.list_item, null);
}
RSSItem item = items.get(position);
if (item != null) {
ImageView image = (ImageView) v.findViewById(R.id.ivImage);
TextView title = (TextView) v.findViewById(R.id.tvTitle);
TextView description = (TextView) v.findViewById(R.id.tvDescription);
if (image != null) {
Drawable d = getResources().getDrawable(R.drawable.icon);
image.setTag(item.getImageURL());
image.setBackgroundDrawable(d);
}
if (title != null) {
title.setText(item.getTitle());
}
if (description != null) {
description.setText(item.toString());
}
}
return v;
}
}
I tried to get Context, but then I don't know how to access the correct ImageView. I appreciate any help!
Add a field to your RSSItem
class that tells the adapter which image to display. In your AsyncTask.onPostExecute
method change that value and then call the notifyDataSetChanged
method of the ArrayAdapter
.
Your getView()
override should use the value you put in your RSSItem to choose which image to display. It will be called again for each item when you call notifyDataSetChanged()
.
Lazy loading of images inside your ArrayAdapter
There's great tutorials online that shows full code examples on how to do this, and also include caching so you don't download images more than once.
- http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/
Additionally the SHELVES android application, free open source app written by one of the google engineers which also has examples of multi-threading, lazy loading and caching of images for an arrayadapter. I highly recommend that you read through this code.
- http://code.google.com/p/shelves/
You could try this if you want to change the imageview from outside of the adapter's getView() function.
List<View> listOfViews = new ArrayList<View>();
listView1.reclaimViews(listOfViews);
for (View v : listOfViews)
{
ImageView image = (ImageView)v.findViewById(R.id.image);
image.setBackgroundDrawable(drawable);
}
精彩评论