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:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
|
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:
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.
And place the following layout file under res/layout/news_entry_list_item.xml
12345678910111213141516171819202122232425262728293031323334353637 |
|
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.
No comments:
Post a Comment