我在项目中为列表项使用不同的布局时遇到了问题。
下面是我的代码:
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;
}
}
一切正常,直到我开始滚动。有时数据推送到错误布局的问题。我知道这可能是因为重用了列表项的视图。但我不明白如何强制适配器在 bindView() 中使用正确的视图?可能这不是很难理解,但我不能:-(谁能告诉我我的问题在哪里?
PS对不起我不完美的英语。