我有一个包含消息列表的聊天窗口。我想像whatsapp那样按日期对消息进行分组。 我的解决方案是将标题添加到所有项目,并使其仅在项目是具有该日期的第一个项目时可见,并将其隐藏在其他位置。我得到每条消息的一年中的日期并进行比较,但我没有得到预期的行为。有时候列表会正确显示日期,然后日期消失,看起来与下图不同。我认为问题是没有按顺序调用getView。
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MessageHolder holder = null;
ChatMessageThread msg = data.get(position);
int msgData = TimingUtils.getDateFromStringTimeStamp(msg.getSendTime());
if(row == null)
{
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MessageHolder();
holder.time = (TextView)row.findViewById(R.id.msg_time);
holder.txtTitle = (TextView)row.findViewById(R.id.list_messages_title);
holder.txtDate = (TextView) row.findViewById(R.id.msg_date);
row.setTag(holder);
}
else
{
holder = (MessageHolder)row.getTag();
}
if (position>0 && msg.getSendTime()!=null ) {
}
holder.txtTitle.setText(msg.getContent());
holder.time.setText(TimingUtils.getFormattedDate(msg.getSendTime()));
holder.txtDate.setText(""+TimingUtils.getFormattedDate(msg.getSendTime()));
LayoutParams lp = (LayoutParams) holder.txtTitle.getLayoutParams();
if (msg.getUserId().equals( GlobalVaribles.account.getUserId())) {
holder.txtTitle.setBackgroundResource(R.drawable.outgoing);
lp.gravity = Gravity.RIGHT;
} else {
holder.txtTitle.setBackgroundResource(R.drawable.incoming);
lp.gravity = Gravity.LEFT;
}
holder.txtTitle.setLayoutParams(lp);
holder.time.setLayoutParams(lp);
//first item only
if (currentTempDate == -1) {
currentTempDate = msgData;
holder.txtDate.setVisibility(View.VISIBLE);
} else {
if (msgData == currentTempDate) {
Log.i("DAY",""+msg.getContent()+ "msgData"+msgData+ "currentTempDate"+currentTempDate);
holder.txtDate.setVisibility(View.GONE);
} else if (msgData>currentTempDate) {
holder.txtDate.setVisibility(View.VISIBLE);
currentTempDate = msgData;
}
}
return row;
}
答案 0 :(得分:0)
我使用数据源获取前一项而不依赖于getView调用
//Current Item
try {
currentItem = (ChatMessageThread) getItem(position);
} catch (Exception e) {
}
try {
previousItem = (ChatMessageThread) getItem(position-1);
} catch (Exception e) {
previousItem = null;
}
if (previousItem ==null) {
previousItem = currentItem;
holder.txtDate.setVisibility(View.VISIBLE);
} else {
if (TimingUtils.getDay(currentItem.getSendTime()) ==
TimingUtils.getDay(previousItem.getSendTime())) {
holder.txtDate.setVisibility(View.GONE);
} else{
holder.txtDate.setVisibility(View.VISIBLE);
}
previousItem = currentItem;
}