Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

ListAdapter inflating multiple objects.

Hello.

I was wondering if there was a way for a ListAdapter to inflate multiple objects within its getView() function. If I had a 'Letters' object and 'Numbers' object and I want to inflate them in the same list, with a single adapter, how would I do it?

Thanks!

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Diego - I think you can create a custom adapter by extending the BaseAdapter class similar to this tutorial: https://guides.codepath.com/android/Using-a-BaseAdapter-with-ListView

Change the adapter constructor in the tutorial to something like this:

private Context context; //context
    private ArrayList<Object> items; //data source of the list adapter

    //public constructor 
    public CustomListAdapter(Context context, ArrayList<Object> items) {
        this.context = context;
        this.items = items;
    }

Since items is an ArrayList of type Object you should be able to use it for both objects of type Letters and Numbers. You probably need to add code in your adapter to determine which of type of object you are dealing with, using the instanceof operator, so that you can properly cast it to that type.

Hope this is helpful.

Thanks! But what I meant to say was inflating multiple objects in the ListView, I should probably fix that.

Kourosh Raeen
Kourosh Raeen
23,733 Points

Can you create a custom class that includes the other two as member variables? That way you give the adapter an ArrayList of the new class. This is the only thing that comes to my mind right now.

Ah, okay. But what if I want to use a ViewHolder to display each object?