0

I have extended an ArrayAdapter that displays items from two separate classes together in one ListView. I pass in ArrayList<ClassA> classAList and ArrayList<ClassB> classBList to the constructor and an update method, and have overridden the supporting functions to display the two classes differently. Having done this, it seems somewhat inelegant.

Is there a more native way to combine multiple classes into a single ListView?

kealist
  • 1,669
  • 12
  • 26
  • Create an interface containing getters for the elements you want displayed and either have `classA` and `classB` implement it or create wrappers for them. You will need to be more specific (ie post code) if you want an answer containing sample code. – daniu Jan 10 '18 at 13:52

2 Answers2

2

It is not elegant because ListView is not designed to show complex data and layouts, your method was pretty much one can do.

If you want to show multiple cell template in an elegant way, you should use RecyclerView.

It's very similar with ListView, you need to implement an adapter which serves as a data source and cell's View factory. Specifically, look at getItemViewType, createViewHolder and bindViewHolder.

Or just search for an solution

Non-maskable Interrupt
  • 3,841
  • 1
  • 19
  • 26
0

Yeah, you can do it by few dirty ways.

The first option is to wrap these classes to a single class that will hold references to ClassA and ClassB. After that, you can work with it like with a normal object.

The second option is to work with both lists at the same time, but you need to work in the adapter in a different way.

First:

@Override
public int getCount() {
    return classAList.size() + classBList.size();
}

Second

@Override
public Object getItem(int position) {
    if(position >= classAList.size()){
         return classBList.get(position  -  classAList.size());
    }
    return classAList.get(position);
}

If you will be using same view for both list all other is same otherwise you should override few more things:
At least
getViewTypeCount() and getItemViewType()

Jakub Gabčo
  • 257
  • 2
  • 14