【问题标题】:Custom adapter smart scrolling自定义适配器智能滚动
【发布时间】:2016-12-22 14:12:57
【问题描述】:

我正在尝试实现我的自定义适配器,但我遇到了性能问题。似乎每次我滚动列表时它都会重新加载。我希望它保持视图并仅显示可见部分。我的列表项有 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 studio 对此行给出建议:

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.

但我使用内部类 Holder 所以我不知道如何解决它。

【问题讨论】:

    标签: android listview android-adapter android-adapterview


    【解决方案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();
        }
    

    【讨论】:

    • 这就是我过去的做法。基本上,它检查 getView() 调用中提供的视图是否为空。如果是,那么它会创建一个新的。否则,因为您拥有标签的所有信息,它只会“回收”查看信息。
    • @JuLes 谢谢,经过一些修改,我设法使它工作。标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多