自定义适配器智能滚动

时间:2016-12-22 14:12:58

标签: android listview android-adapter android-adapterview

我正在尝试实现自定义适配器,但我遇到了性能问题。似乎每次滚动列表时它都会重新加载。我想让它保持视图并仅显示可见部分。我的列表项有imageview和textview。 我的代码:

 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工作室就此行提出建议:

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

它说: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.

但是我使用内部类持有人,所以我不知道如何解决它。

1 个答案:

答案 0 :(得分:1)

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();
    }
相关问题