0

我在项目中为列表项使用不同的布局时遇到了问题。

下面是我的代码:

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对不起我不完美的英语。

4

1 回答 1

0

您对这种方法的看法是错误的:

@Override
public int getItemViewType(int sender_id /* it is position not sender id*/)   
{

}

它不是向您发送sender_id. 而是向您发送位置 0、1、2、3 等等。

并且您必须决定在位置 0、1 等时要做什么。

一个技巧是您可以Cursor在构造函数中保存类级别提供,然后获取该特定位置的数据并sender_id执行剩余步骤。

于 2012-06-13T11:58:09.527 回答