android - Android Listview在滚动时重复项目
问题描述
我查看了其他线程,但看不出我的 listadapter 有什么问题。我有视图持有者模式,并且在 convertview 空检查语句之外设置列表项的所有值。我不确定还有什么其他事情会导致它重复这些项目。
public class ScheduledJobListAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
private ArrayList<Job> jobList;
private Context context;
public ScheduledJobListAdapter(Context context, ArrayList<Job> jobList) {
this.context = context;
this.jobList = jobList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() { return jobList.size(); }
@Override
public Job getItem(int position) { return jobList.get(position); }
@Override
public long getItemId(int position) { return 0; }
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ScheduledViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_scheduled_job,null);
holder = new ScheduledViewHolder();
holder.job = getItem(position);
holder.container = convertView.findViewById(R.id.scheduled_job_layout);
holder.routeOrder = convertView.findViewById(R.id.route_order_textview);
holder.location = convertView.findViewById(R.id.location_textview);
holder.jobRef = convertView.findViewById(R.id.job_ref_textview);
holder.statusIndicator = convertView.findViewById(R.id.status_indicator);
convertView.setTag(holder);
} else {
holder = (ScheduledViewHolder) convertView.getTag();
}
holder.routeOrder.setText(holder.job.getRouteOrder() + "");
holder.location.setText(holder.job.getLocation());
holder.jobRef.setText(holder.job.getJobReference());
return convertView;
}
}
class ScheduledViewHolder {
Job job;
LinearLayout container;
TextView routeOrder;
TextView location;
TextView jobRef;
ImageView statusIndicator;
}
解决方案
这是问题所在:
holder.job = getItem(position);
请记住,当您滚动时,视图可能会被回收,如果您以这种方式分配,分配的工作可能会无意中用于其他职位。要修复它,只需在 if-else 条件之后分配作业:
if (convertView == null) {
// ...
} else {
// ...
}
holder.job = getItem(position); // Update the job by position
holder.routeOrder.setText(holder.job.getRouteOrder() + "");
holder.location.setText(holder.job.getLocation());
holder.jobRef.setText(holder.job.getJobReference());
推荐阅读
- python - 合并列并计算它
- html - 为什么我的 React 样式表媒体查询不起作用?
- python - 如何在谷歌身份验证后使用 django 进行动态 url 重定向
- heroku - 在 Heroku 上存储身份验证配置值的最佳做法是什么?
- python - Pylint 变量名不符合snake_case 命名风格
- scala - Shapeless:在 KList 上映射自然变换
- ios - 如何模仿 App Store 导航结构
- selenium - 无法访问 selenium gird 控制台
- tensorflow - 解释 Keras Transformer 官方示例中的注意力
- mysql - MySQL中的多个字符串文字