Search code examples
javaandroidlistviewlistadapter

Can't use List<String> when implementing CustomListAdapter android


I have a collection of animal objects that are in a polymorphic hierarchy (ie Animal > Reptile > Snake). I want to create a List view where each item in the list is inflated with a different layout depending on the object type (eg one item layout for reptiles, one for cats, one for primates, etc). This activity is just the categories, not the actual list of animals. So I just want to create a "group" item.

To do this, I'm trying to just use a list of all of the possible types of animals (again, reptile, primate, cat, etc). in the form of a List collection. How can I use a CustomListAdapter to accomplish this? It doesn't seem to want to let me give the adapter a List of Strings, it wants a List of Objects.


Solution

  • Just check the type by using switch or if statement and inflate accordingly:

    Here is a sample code:

      @Override 
        public View getView()
        {
            View row = null;
                if (activity.equalsIgnoreCase("Ni_activity") || activity.equalsIgnoreCase("Current_NI_Activity") || activity.equalsIgnoreCase("Ni_Test_Activity")) {
                    row = inflater.inflate(R.layout.ni_spinner_row, parent, false);
                } else if (activity.equalsIgnoreCase("RFTestActivity")) {
                    row = inflater.inflate(R.layout.spinner_row, parent, false);
                } else if (activity.equalsIgnoreCase("SiteInfoFragment") || activity.equalsIgnoreCase("LayerInfoFragment")) {
                    row = inflater.inflate(R.layout.site_frag_spinner, parent, false);
                }
    
                TextView tvCategory = (TextView) row.findViewById(R.id.tvCategory);
                tvCategory.setTypeface(null, Typeface.BOLD);
                try {
                    tvCategory.setText(data.get(position));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return row;
        }