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などのときに何をするかを決定する必要があります。

1つのトリックは、コンストラクターにクラスレベルのCursor提供を保存してから、その特定の位置のデータを取得sender_idし、残りの手順を実行できるようにすることです。

于 2012-06-13T11:58:09.527 に答える