Niestandardowy adapter do wyświetlania listy z różnymi elementami
Chcę mieć podgląd listy z różnymi typami elementów w każdym wierszu widoku listy. Wiem, że muszę użyć niestandardowego adaptera, który rozszerza BaseAdapter, a nie ArrayAdapter, ale potem nie wiem, jak podejść do problemu. Poprzednio próbowałem wykonać adapter w ten sposób:
public class MyArrayAdapter<T> extends ArrayAdapter<T> {
LayoutInflater mInflater;
int[] mLayoutResourceIds;
private final Context context;
public MyArrayAdapter(Context context, int[] textViewResourceId, List<T> objects) {
super(context, textViewResourceId[0], objects);
this.context = context;
mInflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
mLayoutResourceIds = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
int type = getItemViewType(position);
// instead of if else you can use a case
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == TYPE_ITEM1) {
//infalte layout of type1
row = inflater.inflate(R.layout.item1, parent, false);
}
if (type == TYPE_ITEM2) {
//infalte layout of type2
} else {
//infalte layout of normaltype
}
}
return super.getView(position, convertView, parent);
}
@Override
public int getItemViewType(int position) {
if (position== 0){
type = TYPE_ITEM1;
} else if (position == 1){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type; //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public int getViewTypeCount() {
return 3; //To change body of overridden methods use File | Settings | File Templates.
}
}
ale gdy uruchomiłem działanie, otrzymałem błąd:
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
i rozumiem dlaczego, ale nie zamierzam używać textView we wszystkich moich układach. Potrzebuję wskazówek, jak postępować. Dzięki
Zmiana tła rodzica linearLayout w moim item1.xml powoduje wyjątek zerowego wskaźnika. Działa bez wyjątku zerowego wskaźnika, jeśli zostawiam tło w pierwotnym stanie