作者:手机用户2602881561 | 来源:互联网 | 2022-12-09 11:44
所以我有一个listview从基于Room的SQLite数据库中提取数据.它看起来很好地读取数据,但是当页面加载时我会得到前10个条目(显示的大小),当我尝试向下滚动列表视图时,它会重新开始并开始获取条目在列表的开头再次.屏幕截图上的红色圆圈显示了列表的顶部和底部以及存在的重复.
public class NeighborhoodListAdapter
extends ArrayAdapter {
private List neighborhood;
Context context;
// View lookup cache
private static class ViewHolder {
TextView cityName;
}
public NeighborhoodListAdapter(List neighborhood, Context context) {
super(context, R.layout.object_main_citydetailsrow, neighborhood);
this.cOntext= context;
this.neighborhood = neighborhood;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
LivingCity city = getItem(position);
ViewHolder viewHolder;
if (cOnvertView== null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
cOnvertView= inflater.inflate(R.layout.object_main_citydetailsrow, parent, false);
viewHolder.cityUid = (TextView) convertView.findViewById(R.id.cityrow_uid);
viewHolder.cityUid.setText(String.format(Locale.ENGLISH,"#%d", city.getUid()));
}//city.getUid() returns an int
}catch (Exception e){
Log.d("editCity: ", e.toString());
}
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Return the completed view to render on screen
return convertView;
}
}
而我正在开始
void loadNeighborhood() {
neighborhoodDB = Neighborhood.getAppDatabase(this);
neighborhood = neighborhoodDB.getNeighborhood();
}
从数据库助手中提取已排序的列表
public List getNeighborhood() {
List neighborhood = cityDao().getAll();
Collections.sort(neighborhood,
new Comparator() {
@Override
public int compare(LivingCity city1, LivingCity city2) {
return Integer.valueOf(city1.getUid()).compareTo(city2.getUid());
} //I thought this sort operation might be whats wrong but same error with it commented out
});
return neighborhood;
}
编辑:此外,如果我反复滚动到底部而不上升,我可以欺骗它来洗牌一些上面的项目,如截图所示(橙色).
1> K Neeraj Lal..:
滚动ListView
循环旧视图时.但是,只有在新行膨胀时才更新值.新行的通货膨胀不会一直发生,它会重复使用旧行.这就是你再次看到旧价值的原因.移动块下方的线,viewHolder.cityUid.setText();
如下if-else
所示.
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
LivingCity city = getItem(position);
ViewHolder viewHolder;
if (cOnvertView== null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
cOnvertView= inflater.inflate(R.layout.object_main_citydetailsrow, parent, false);
viewHolder.cityUid = (TextView) convertView.findViewById(R.id.cityrow_uid);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//city.getUid() returns an int
viewHolder.cityUid.setText(String.format(Locale.ENGLISH,"#%d", city.getUid()));
// Return the completed view to render on screen
return convertView;
}