Android ListView:游标适配器使用了不正确的项类型
我在项目中使用不同的列表项布局时遇到问题 下面是我的代码:Android ListView:游标适配器使用了不正确的项类型,android,Android,我在项目中使用不同的列表项布局时遇到问题 下面是我的代码: private class ChatAdapter extends CursorAdapter { private LayoutInflater mInflater; private static final int OWN_MESSAGE = 0; private static final int INTERLOCUTOR_MESSAGE = 1; public ChatAdapter(Contex
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中使用正确的视图?
也许这并不难理解,但我不能:-
谁能告诉我哪里出了问题
另外,很抱歉我的英语不太好。你对这种方法的看法是错误的:
@Override
public int getItemViewType(int sender_id /* it is position not sender id*/)
{
}
它不是向您发送发件人id,而是向您发送位置0、1、2、3等等
当位置为0、1等时,您必须决定要做什么
一个技巧是,您可以保存构造函数中提供的类级游标,然后获取该特定位置上的数据,并让发送者id执行其余步骤。您完全正确。我没有正确理解getItemViewType方法。谢谢你帮助我!现在一切都好了。