简体   繁体   中英

Android Listview is repeating items when scrolled

I have looked at other threads and I cannot see what is wrong with my listadapter. I have the view holder pattern and I am setting all the values for the list item outside of the convertview null check statement. Im not sure what other things would cause it to repeat the items.

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;
}

Here's the problem:

holder.job = getItem(position);

Remember the views may be recycled as you scroll, and the job assigned maybe used unintentionally for other positions if you assigned it that way. To fix it, simply assign the job after the if-else condition:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM