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