Adapter can work with different views. You should override two methods: getViewTypeCount()
and getItemViewType(int position)
. In your case:
private static final int TYPES_COUNT = 2;
private static final int TYPE_LEFT = 0;
private static final int TYPE_RIGHT = 1;
@Override
public int getViewTypeCount() {
return TYPES_COUNT;
}
@Override
public int getItemViewType (int position) {
if (getItem(position).left) {
return TYPE_LEFT;
}
return TYPE_RIGHT;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
Holder holder;
OneComment coment = getItem(position);
if (row == null) {
holder = new Holder();
if (getItemViewType (position) == TYPE_LEFT) {
row = inflater.inflate(R.layout.listitem_left_chat, null, false);
holder.message = (TextView) row.findViewById(R.id.comment);
holder.box = (CheckBox) row.findViewById(R.id.checkBox1);
} else {
row = inflater.inflate(R.layout.listitem_right_chat, null, false);
holder.message = (TextView) row.findViewById(R.id.comment2);
holder.box = (CheckBox) row.findViewById(R.id.checkBox2);
}
row.setTag(holder);
} else {
holder = (Holder)row.getTag();
}
holder.message.setText(coment.comment);
holder.box.setChecked(coment.left);
return row;
}
public class Holder {
TextView userName;
TextView message;
CheckBox box;
}
UPD:
Explanation:
getItemViewType
should return an integer that identifies what type of View that will be created by getView(int, View, ViewGroup)
for the specified item. Two views should return the same result if one can be converted to the other in getView
.
getViewTypeCount
should return an integer with the number of types of Views that the Adapter will handle.
Behind the scenes Android uses the View type to determine what type of View should be passed in to the getView
method. You can think of it as creating multiple buckets of Views that can be reused and thus avoid the penalty of inflating a new view each time a new list item becomes visible.
As the user scrolls down the ListView the framework will recycle rows that are no longer visible and add them to the appropriate bucket for reuse. When a new Header or Event item comes into view the framework will check to see if one of those views already exists in the bucket of recycled views, if so it will be passed in as the convertView
to getView
method.