0

我在 android 聊天应用程序中有一个用于 listView 的自定义 ArrayAdapter。我在 editText 组件中输入了一些文本,然后在按下按钮时提交文本。

问题是,当我的自定义适配器中的 getView 方法被调用时,整个列表都会被刷新,并且我列表中的每一行都与最后提交的信息相同。

有人知道如何使用自定义 ArrayAdapter 和其他行在 listView 中添加一行以获得原始文本吗?

这就是我调用适配器的方式:

m_discussionThread = new ArrayList<String>();
    m_discussionThreadAdapter = new ChatListAdapter(this, m_discussionThread);
    list.setAdapter(m_discussionThreadAdapter);

    Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {


            String text = message.getText().toString();

            Message msg = new Message(to, Message.Type.chat);
            msg.setBody(text);
            m_connection.sendPacket(msg);               
            m_discussionThread.add(text);   
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_discussionThreadAdapter.notifyDataSetChanged();

                }
            });
        }
    });

这是适配器:

public ChatListAdapter(Context context, ArrayList<String> chatValue) {  
    super(context,R.layout.list_row_layout_even, chatValue);
    this.context = context;     
    this.chatValue = chatValue;     
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);         
    View rowView  = inflater.inflate(R.layout.list_row_layout_even, parent, false);
    TextView chatText = (TextView) rowView.findViewById(R.id.chat_message);
    chatText.setText(chatValue.get(chatValue.size()-1).toString());
    return rowView;
4

1 回答 1

1

在底部附近,您将获得 data element chatValue.size()-1。这意味着通过 getView() 加载的每个视图都将具有最后一个数据元素的属性。您应该改用position. 例子:

private Context mContext;
private LayoutInflater mInflater = null;

private ArrayList<String> mChatValue;

public ChatListAdapter(Context context, ArrayList<String> chatValue) {  
    super(context,R.layout.list_row_layout_even, chatValue);
    mContext = context;     
    mChatValue = chatValue;     
}

private LayoutInflater getInflater(){
    if(mInflater == null)
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    return mInflater;       
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView;
    if(convertView == null) // Only inflating if necessary is great for performance
        rowView = getInflater().inflate(R.layout.list_row_layout_even, parent, false);
    else
        rowView = convertView;

    TextView chatText = (TextView) rowView.findViewById(R.id.chat_message);
    chatText.setText(mChatValue.get(position));

    return rowView;
}
于 2012-08-11T13:45:40.983 回答