这是我的getView()
:
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = null;
if (convertView == null) {
//MessageModel mm = messageModels.get(position);
if(!messageModels.get(position).isIncoming()){
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_messages_outgoing, null);
}else {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_messages_incoming, null);
}
//only for debugging purpose
Log.i(tag, position+", id: "+messageModels.get(position).getId()+", isIncoming: "+
messageModels.get(position).isIncoming()+", msg: "+messageModels.get(position).getMessage());
holder = new Holder();
holder.tvMessage = (TextView) convertView.findViewById(R.id.tvMessage);
holder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
convertView.setTag(holder);
} else {
holder = (Holder)convertView.getTag();
}
holder.tvMessage.setText(messageModels.get(position).getMessage());
holder.tvTime.setText(messageModels.get(position).getTime());
return convertView;
}
从日志中我发现以下内容:
0, id: 11, isIncoming: true, msg: hi
1, id: 14, isIncoming: false, msg: hmmm
0, id: 11, isIncoming: true, msg: hi
这是最后一个重复的第一个索引。我尝试了更大的项目编号,它总是调用这样的位置:0, 1, 2, 3, ... n-2, 0
所以我错过了n-1
(最后)位置。我应该在哪里改变?
答案 0 :(得分:0)
覆盖适配器类中的函数getCount()。并返回 messageModels.size()来自那里,看起来你可能会回来 (messageModels.size() - 1)从那里开始。
@Override
public int getCount() {
return messageModels.size();
}
答案 1 :(得分:0)
实际上我布局中的这一行android:stackFromBottom="true"
导致了这一点。我删除了它,问题解决了。
答案 2 :(得分:0)
在我的情况下,最后一项返回位置0:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = View.inflate(getContext(), R.layout.foo_row, null);
fooModel = this.getItem(position);
//proceed with fooModel
}
return view;
}
将其更改为以下即可解决问题:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.foo_row, parent, false);
}
fooModel = this.getItem(position);
//proceed with fooModel
return convertView;
}
也不要忘记在if-else条件检查中重置视图属性,例如:
if (fooModel.name != null) { yourView.setText(fooModel.name); }
else { yourView.setText(''); }