为此,您必须为列表视图创建自定义适配器,而不是为左侧项目(即发送的项目)和右侧项目(即接收的项目)创建两个单独的适配器。
这意味着您已经在一个自定义适配器中管理发送/接收的消息。
例如
// Sample messages inside MessageActivity
void initMessages() {
HashMap<String, String> messageSent = new HashMap<String, String>();
messageSent.put("message", "Hi");
messageSent.put("type", "sent");
messageSent.put("date", "");
HashMap<String, String> messageReceived = new HashMap<String, String>();
messageSent.put("message", "Hello");
messageSent.put("type", "received");
messageSent.put("date", "");
ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();
messages.add(messageSent);
messages.add(messageReceived);
MessageAdapter adapter = new MessageAdapter(mContext, messages);
setListAdapter(apater);
}
// adapter class
class MessageAdapter extends ArrayAdapter<HashMap<String, String>> {
LayoutInflater inflater;
public MessageAdapter(Context context, ArrayList<HashMap<String, String>> data) {
super(context, R.layout.raw_message, data);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.raw_message, null);
holder = new ViewHolder();
holder.txtSent = convertView.findViewByTag("sent");
holder.txtReceived = convertView.findViewByTag("received");
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
HashMap<String,String> message = getItem(position);
boolean sent = message.get("type").equals("sent");
if(sent) {
holder.txtSent.setVisibility(View.VISIBLE);
holder.txtSent.setText(message.get("message"));
holder.txtReceived.setVisibility(View.GONE);
} else {
holder.txtSent.setVisibility(View.GONE);
holder.txtReceived.setText(message.get("message"));
holder.txtReceived.setVisibility(View.VISIBLE);
}
}
class ViewHolder {
TextView txtSent;
TextView txtReceived;
}
}
// raw_message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:tag="sent"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:tag="received"/>
</RelativeLayout>