Usually an Adapter will have this to optimize the performance of the listview:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item1, null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
and view holder is:
public static class ViewHolder {
public TextView textView;
}
But what if i have different type of rows, like 1 with an ImabeView, 1 with a CheckBox, 1 with EditText
1st thing will be:
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType(int position) {
//if something
return 0
//if something else
return 1
//if something different
return 2
}
and in getView();
getView(int position, View convertView, ViewGroup parent){
//if convetView == null, getItemViewType(position) and depending on the type inflate respective layout
convertView.setTag(holder);
//else
holder = (ViewHolder)convertView.getTag();
}
But what about the ViewHolders, should i have 3 Different ViewHolders and depending on the type……..setTag for respective Holder?
I could find any example for something like this. Actually i haven’t seen anu ListView using more than 1 ViewHolder.
Am i doing it the right way??
Thank You
There is nothing stopping you from declaring all possible views from all of
ListView‘s layouts in a singleViewHolderclass(so theViewHolderwill hold a reference to anImageView,CheckBoxandEditTextfrom your example).In the
getViewmethod when theconvertViewisnullyou will set the views in theViewHolderonly for that type of row, all other view references in theViewHolderwill benull. When it’s time to use the views from theViewHolderjust see with which type of row your working and only get the views from theViewHolderthat belong to that row.You could also use three
ViewHolderclasses for each type of row(and set them for each particular row when you inflate it), but I think the first versions is nicer. In the end you could go either way as long as you properly implement the multiple row types mechanism.