首页 > 解决方案 > 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;
}

标签: androidlistview

解决方案


这是问题所在:

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());

推荐阅读