I’ve got a problem using different layouts for list items in my project.
Here is my code below:
private class ChatAdapter extends CursorAdapter {
private LayoutInflater mInflater;
private static final int OWN_MESSAGE = 0;
private static final int INTERLOCUTOR_MESSAGE = 1;
public ChatAdapter(Context context, Cursor c) {
super(context, c, false);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView text = (TextView) view.findViewById(R.id.chat_message_text);
final String message = cursor.getString(MessagesQuery.MESSAGE_TEXT);
text.setText(message);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup group) {
View view = null;
final int sender_id = cursor.getInt(MessagesQuery.SENDER_ID);
final int messageType = getItemViewType(sender_id);
switch (messageType) {
case OWN_MESSAGE:
view = (View) mInflater.inflate(R.layout.list_item_message_own, null);
break;
case INTERLOCUTOR_MESSAGE:
view = (View) mInflater.inflate(R.layout.list_item_message_interlocutor, null);
break;
}
return view;
}
@Override
public int getItemViewType(int sender_id) {
return (sender_id == Prefs.getIntProperty(mContext, R.string.key_user_id)) ? OWN_MESSAGE
: INTERLOCUTOR_MESSAGE;
}
@Override
public int getViewTypeCount() {
return 2;
}
}
Everything is OK until I start scrolling. The problem that sometimes data pushing to wrong layout. I understand that this is probably because of reusing Views for list items.
But I don’t understand how to force adapter use correct view in bindView()?
Probably this isn’t very hard to understand, but I can’t 🙁
Can anyone tell me where is my problem?
P.S. Sorry about my imperfect English.
Your perception about this method wrong:
it is not sending you the
sender_id. rather it is sending you the position 0, 1, 2, 3, and so on.and you have to decide what to do when it is position 0, 1, and so on.
One trick is that you can save class level
Cursorprovide in your constructor and then get the data on that particular position and get thesender_iddo the remaining step.