android列表适配器不会正确地扩展视图

时间:2016-04-07 13:43:18

标签: android listview android-arrayadapter layout-inflater

我正在尝试使用android中的自定义列表视图适配器,以便我可以在列表视图中使用两个不同的布局,左右消息来扩展聊天消息项列表,如适配器中所示:

package com.example.user.normalinterface;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class messageAdapter extends ArrayAdapter<chatMessage> {

    private Activity activity;
    private List<chatMessage> messages;

    public messageAdapter(Activity context, int resource, List<chatMessage> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.messages = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        int layoutResource = 0; // determined by view type
        chatMessage chatMessage = getItem(position);
        int viewType = getItemViewType(position);

        if (viewType==0) {
            layoutResource = R.layout.chat_bubble_right;
        } else {
           layoutResource = R.layout.chat_bubble_left;
        }

        if (convertView != null) {
            holder = (ViewHolder) convertView.getTag();
        } else {
            Log.d("NOTICE", "generated");
            convertView = inflater.inflate(layoutResource, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }

        //set message content
        holder.message.setText(chatMessage.getContent());

        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        chatMessage chatMessage = getItem(position);
        if (chatMessage.isMine()) {
            return 0;
        } else {
            return 1;
        }
    }


    private class ViewHolder {
        private TextView message;

        public ViewHolder(View v) {
            message = (TextView) v.findViewById(R.id.txt_msg);
        }
    }
}

这是聊天消息的课程:

public class chatMessage {

private String content;
private boolean isMine;

public chatMessage(String content, int senderID, int userID) {
    this.content = content;

    if(userID==senderID)
    {
        isMine = true;
    }
    else
    {
        isMine = false;
    }
}

public String getContent() {
    return content;
}

public boolean isMine() {
    return isMine;
}
}

现在问题在于:通过记录生成的每个视图,我只找到5个日志说它已生成,但事实证明只有我在列表视图中看到的前5个视图在正确的布局,以下是截图:

screenshot_1 screenshot_2

实际上订单应该是:

right
left
left
left
right
right
right

我也尝试记录资源的条件并且它们都是正确的,不知何故,在我查看布局后的前5个项目之后不再正确(我从下面开始列表视图所以前5个项目从底部是正确的)。有没有办法解决这个问题?

0 个答案:

没有答案