Chapter 6. Working with lists and adapters

 

Lists and adapters are two of the main concepts to master in Android development. In this chapter, you’ll learn several tips and tricks you can use with lists and adapters.

Hack 24 Handling empty lists: Android v1.6+

A common way to show data to the user in mobile platforms is to place it inside a list. When you do this, you need to handle two cases: the ordinary list full of items and an empty state. For the list, you’ll use a ListView, but how do you handle the empty state? Fortunately, there’s an easy way to achieve this. Let’s look at how to do it.

ListView and other classes that extend AdapterView easily handle emptiness through a method called setEmptyView(View). When the AdapterView needs to draw, it’ll draw the empty view if its Adapter is null, or the adapter’s isEmpty() method returns true.

Let’s try an example. Imagine we want to create an application to handle our TODO list. Our main screen will be a ListView with all our TODO items, but when we launch it for the first time, it’ll be empty. For our empty state, we’ll draw a nice image. Following is the XML layout:

Hack 25 Creating fast adapters with a ViewHolder: Android v1.6+

Hack 26 Adding section headers to a ListView: Android v1.6+ Contr- ributed by Chris King

Hack 27 Communicating with an Adapter using an Activity and a del- legate: Android v1.6+

Hack 28 Taking advantage of ListView’s header: Android v1.6+

Hack 29 Handling orientation changes inside a ViewPager: Android v1.6+

Hack 30 ListView’s choiceMode: Android v1.6+