Skip to content

Lots of Lists: Part 2, List with custom objects and adapter

Custom Objects

Frequently you’ll have some sort of object model that describes the kinds of data you’re trying to show– in our example, we’re going to have a very simple, immutable class called NewsEntry that encapsulates information about a fictitious news entry. Our use cases include a title, author, date of posting, and an icon to show. For simplicity we’ll assume the icon is a local resource in the APK.

Here is our NewsEntry class:

In our previous tutorial, we used an ArrayAdapter that took simple Strings and bound them to a simple TextView layout for each String in the list. Since we’re using more complex objects, such as NewsEntry, we can’t necessarily rely on a toString() to satisfy our complex view. Android actually provides a SimpleAdapter class that could serve our needs, but for the sake of depth we’ll extend and override ArrayAdapter for our purposes.

NewsEntry List Item Layout

We need to define how each item in the list is going to look. We won’t be focusing too much on the layout contents, as we have some excellent tutorials for layouts all by themselves here: Android Layout Tutorial

Here’s the example layout we’re going with:

Lots of Lists 2: News Entry Item Layout

Lots of Lists 2: News Entry Item Layout

This is the final layouts we came up with (plus two icons to use):

Place the following icons under res/drawable-mdpi/. They should be located at res/drawable-mdpi/news_icon_1.png and res/drawable-mdpi/news_icon_2.png when finished.

News Icon Variety #1

News Icon Variety #1

News Icon Variety #2

News Icon Variety #2

And place the following layout file under res/layout/news_entry_list_item.xml

As you can see, we used a RelativeLayout to position our title, icon, and subtitle views. To learn more about RelativeLayouts, check this out: Android Layout Tutorial – RelativeLayouts.

On the next page we’ll look at the implementation of our custom adapter, NewsEntryAdapter.

{ 5 } Comments

  1. zAo | July 1, 2012 at 9:02 am | Permalink

    Hi, should
    android:text=”@string/hello” />
    Not be
    android:text=”@string/hello_world” />


  2. Gav Newalkar | July 2, 2012 at 3:25 am | Permalink

    Excellent tutorial. Thanks for the explanations, this is awesome.

  3. Jonathan | February 18, 2014 at 10:07 am | Permalink

    Google discourages the use of getter/setters (as you used in the NewsEntry class) for performance reasons.

  4. Oscar | May 6, 2014 at 4:19 am | Permalink

    Thank you!!

  5. Sheridan | September 27, 2014 at 8:16 am | Permalink

    Thanks for the info!

{ 1 } Trackback

  1. […] managed to implement a great listview that I found here but I can’t seem to add an onclicklistener I just want to be able to do an action when I […]

Post a Comment

Your email is never published nor shared. Required fields are marked *