Custom adapter smart scrolling

526 views Asked by At

I am trying to implement my custom adapter but I am facing performance issues. It seems that every time I scroll the list it is loaded all over again. I want it to hold the view and display only the visible part. My list item has imageview and textview. My code:

 class CustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<CounselorInfo> counselors;
    private static LayoutInflater inflater = null;

    CustomAdapter(Context context, ArrayList<CounselorInfo> counselors) {

        this.context = context;
        this.counselors = counselors;

        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return counselors.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class Holder
    {
        TextView textView;
        ImageView imageView;
    }@Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        Holder holder = new Holder();
        View rowView = inflater.inflate(R.layout.counselors_list, null);

        holder.textView = (TextView) rowView.findViewById(R.id.nameCounselor);
        holder.imageView = (ImageView) rowView.findViewById(R.id.imageCounselor);

        holder.textView.setText(counselors.get(position).getName());
        ImageLoadTask imageLoad = new ImageLoadTask(" http:// " + counselors.get(position).getImageURL(), holder.imageView);
        imageLoad.execute();

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something
            }
        });

        return rowView;
    }
}

Android studio gives suggestion on this row:

View rowView = inflater.inflate(R.layout.counselors_list, null);

it says: Unconditional layout inflation from view adapter: Should use View Holder pattern (use recycled view passed into this method as the second parameter) for smoother scrolling.

But I use inner class Holder so I don't know how to solve it.

1

There are 1 answers

2
JuLes On BEST ANSWER

add this on getView():

    final Holder holder;

    if (convertView == null) {
        holder = new Holder();

        View rowView = inflater.inflate(R.layout.counselors_list, null);
        holder.textView = (TextView) rowView.findViewById(R.id.nameCounselor);
        holder.imageView = (ImageView) rowView.findViewById(R.id.imageCounselor);

        convertView.setTag(holder);

    } else

    {
        holder = (Holder) convertView.getTag();
    }