Home » Android » Android Core » Android ListView: Custom Adapter with ImageView

About Francesco Azzola

I'm a senior software engineer with more than 15 yrs old experience in JEE architecture. I'm SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. I'm an android enthusiast and i've worked for long time in the mobile development field.

Android ListView: Custom Adapter with ImageView

In previous post we talked about custom adapter. We used a quite simple adapter with just a TextView. We want to expand the idea described before and introduce an image for each planet. To do it we have to modify the layout and other code parts to handle the user click on each item. We want that each row in the ListView looks like:
 

The first thing we have to do is to modify the layout and use a RelativeLayout instead of a simple LinearLayout. Our layout looks like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/img"
        android:layout_toRightOf="@+id/img"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/dist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_gravity="center"
        android:layout_marginTop="2dip"
        android:layout_toRightOf="@id/img"
        android:gravity="right"
        android:textSize="8dp"
        android:textStyle="italic" />

</RelativeLayout>

The layout shown above is quite trivial and we don’t need to explain it. Then we have to modify the custom adapter in order to handle the images and the holder class. The holder class becomes:

private static class PlanetHolder {
    public TextView planetNameView;
    public TextView distView;
    public ImageView img;
}

and the adapter becomes:

public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    PlanetHolder holder = new PlanetHolder();

    // First let's verify the convertView is not null
    if (convertView == null) {
        // This a new view we inflate the new layout
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.img_row_layout, null);
        // Now we can fill the layout with the right values
        TextView tv = (TextView) v.findViewById(R.id.name);
        TextView distView = (TextView) v.findViewById(R.id.dist);
        ImageView img = (ImageView) v.findViewById(R.id.img);

        holder.planetNameView = tv;
        holder.distView = distView;
        holder.img = img;

        v.setTag(holder);
    }
    else 
        holder = (PlanetHolder) v.getTag();

    System.out.println("Position ["+position+"]");
    Planet p = planetList.get(position);
    holder.planetNameView.setText(p.getName());
    holder.distView.setText("" + p.getDistance());

    holder.img.setImageResource(p.getIdImg());

    return v;
}

In this way for each row in the ListView we set not only the planet name in the TextView but the ImageView also, with the image relative to the planet. If we run the app we have something like it:

Well i didn’t use the right images for the planets it is just a way to show you how to use images!!!. You have to resize and make the images better in your app!

Now if you click on an item you get a ClassCastException. Why? Well, you try to cast, inside the onItemClick method, a RelativeLayout to a TextView and it is impossible.

Handle user item click

If you want to handle user click on each item you have to modify the code inside the method lv.setOnItemClickListener. First of all we have to find the item position chosen by the user and we could do it or using the position parameter in public void onItemClick(AdapterView<?> parentAdapter, View view, int position,  long id) or we could ask to the SO to find the right position in this way:

int pos = lv.getPositionForView(view);

In this way we know the position of the item clicked by the user. Once we know it, it is really simple to extract the information, because having the reference to the array of items we simply do:

Planet planet =  aAdpt.getItem(pos);

So when user clicks on an item inside the ListView we have:

 

Reference: Android ListView: Custom Adapter with ImageView from our JCG partner Francesco Azzola at the Surviving w/ Android blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

7 comments

  1. I’ve tried this solution, and everything seems in order except for the fact that when I run the app I don’t get the images showing up. I’ve made planet images with the same names (mars, mercury, etc.), but nothing appears.

  2. Thank you for information specially holder static object of inner class. Very Nice tutorial

  3. i want to add contacts to this listview with images(contact pic)…any help.. pls sir

  4. Hey francesco,
    Thanks for sharing this tutorial with us. You explained custom adapter really well.

  5. LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    The “context” is from?

  6. Very nice! No errors, modern approach!!!
    Vogella.com should take example from you! I lost 2 hours because of their outdated non-functional code.
    Good job guys!

Leave a Reply

Your email address will not be published. Required fields are marked *

*


− 3 = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close