Inflating different xml layouts in an Android ListView for different Objects.
While working on the Ambient Dynamix Project, I needed to create a listview which contains a non fixed number of headers each one followed by some list items.
A common solution is to use the MergeAdapter. A MergeAdapter object exposes the addAdapter(), addView() and addViews() methods. The demo included in the repo is pretty self explanatory.
But in case of the MergeAdapter, I’d need to keep track of multiple adapters, one for each of the list, which can be a bit of pain in case I need some data back from the adapters. So, I wrote a custom adapter which could inflate different layouts depending on the type of item.
###Writing the Custom Adapter :
Create a public class which contains the types of items in the list view.
Create another public class with two fields, an int and an Object. We’ll use an ArrayList of objects of this class as the data source for our custom adapter. The idea is to use the use the type value to inflate the relevant xml layout inside the adapter.
We’ll assume that we also have two classes whose objects contain the data for the different list items. Let’s call them HeaderObject and ListItemObject. For the sake of simplicity, we’ll just add a String field to both the classes. But you’ll need to use this method only if you have very different data for the views and hence they cannot be stored by the same object.
The custom adapter :
Creating the adapter:
I am not too sure if this is the best way to go about this and there definitely is an overhead of typecasting every object but it works!