我在listview的自定义适配器中的getView()方法中发生了一些奇怪的事件。似乎缓存视图只在应用程序结束时更新。我已经阅读了很多教程,但从未见过像这样的问题。
当我将第一项添加到适配器时,一切都很好 - convertView为null,我给视图充气并返回它。但是,当我尝试添加第二个项目时,getView()会发送与位置0和1完全相同的convertView(即使位置1它应该为null),从而产生相同的项目。
重新启动应用后,每个添加的项目都会被正确查看(数据被序列化),但尝试添加更多项目仍会导致视图与第一个相同。
我确定问题在于适配器,getView(),因为当我停止使用convertView并且每次只是膨胀项目时,它完全正常。
这就是我的方法的样子。 mNames是Vector;当它改变时,它被序列化并通知适配器。此向量设置适配器计数(请参阅getCount)。在传递给适配器之前,它在onCreate()中被反序列化。
@Override
public int getCount() {
return mNames.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.grouplist_listview_item, null);
//just saying, there are more subviews; I didn't find it relevant
((TextView)convertView.findViewById(R.id.grouplist_listview_item_text)).setText(mNames.elementAt(position));
}
return convertView;
}
所以我真的不明白这两件事:
答案 0 :(得分:0)
我认为你需要阅读一本好的教程。我知道好的网页@ Using an ArrayAdapter with ListView。搜索文本"定义适配器"查看getView()
代码。
代码段:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
// Populate the data into the template view using the data object
tvName.setText(user.name);
// Return the completed view to render on screen
return convertView;
}
注意:代码使用setText
方法。这将使用ArrayAdapter和您的布局测试您的代码。