Sajith Rupasinghe
Sajith Rupasinghe

Reputation: 343

Dynamically change image of a Listview/ArrayAdapter

I have a ListView that I use to display file/folder hierarchy inside my application. I'm using a custom layout with an ImageView and a TextView. I want to change the image of the ImageView according to TextView text is ether folder or file. Can I do this without using a custom ArrayAdapter or if I have to use a custom ArrayAdapter how can I change ImageView icon in the runtime.?

Upvotes: 0

Views: 3280

Answers (4)

Umer Farooq
Umer Farooq

Reputation: 7486

Use this getView() method in your custom adapter class.

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View newRowView = convertView;
    ViewHolder viewHolder;


    if(newRowView == null)
    {
    LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    newRowView = inflator.inflate(R.layout.my_list, parent,false); 
    viewHolder = new ViewHolder();

    viewHolder.name = (TextView) newRowView.findViewById(R.id.textInList);

    viewHolder.image = (ImageView) newRowView.findViewById(R.id.iconInList);

    newRowView.setTag(viewHolder);

    }
    else
    {
        viewHolder = (ViewHolder) newRowView.getTag();

    }


    viewHolder.image.setImageDrawable(textImages[position]);

    viewHolder.name.setText(names[position]);

    return newRowView; 
}



static class ViewHolder
{
    TextView name;
    ImageView image;

}

Here textImages & names are the arrays which I passed to the custom adapter from the activity class.

This is the most memory efficient and fast way.

Upvotes: 0

Jayamohan
Jayamohan

Reputation: 12924

You can use ImageView.setImageResource(int) method.

Upvotes: 0

rachit
rachit

Reputation: 1996

You can check that in getView function of custom adapter and set imageview according to the textview. see this example for custom array adapter.

Upvotes: 0

Jules
Jules

Reputation: 15199

You will have to use a custom adapter any time you need more than one variable item per entry in the list (i.e. in your case you have two, the ImageView and the TextView). Changing data at runtime is most easily achieved by calling ArrayAdapter.notifyDataSetChanged().

Upvotes: 1

Related Questions