滚动recyclerview时滞后

时间:2016-04-16 17:10:03

标签: java android

这是我的适配器代码:

public class CatAdapter extends RecyclerView.Adapter<CatAdapter.ViewHolder> {
ArrayList<CatModel> objects_;
Context context;
Class res = R.drawable.class;

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView cat_text,cat_des;
    ImageView cat_img;

    public ViewHolder(View v) {
        super(v);
        cat_text = (TextView) v.findViewById(R.id.cat_txt);
        cat_des = (TextView) v.findViewById(R.id.cat_des);
        cat_img = (ImageView) v.findViewById(R.id.cat_img);
    }
}

public CatAdapter(ArrayList<CatModel> arrayList, Context context) {
    this.context = context;
    objects_ = arrayList;
}

@Override
public CatAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_list_view, parent, false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.cat_text.setText(objects_.get(position).txt);
    holder.cat_des.setText(objects_.get(position).des);
    try {
        Field field = res.getField(objects_.get(position).img);
        int drawableId = field.getInt(null);
        holder.cat_img.setImageDrawable(context.getResources().getDrawable(drawableId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public int getItemCount() {
    return objects_.size();
}
}

CatModel上课

public class CatModel {
    public String txt,img,des;
}

CatModel.img是我drawables的{​​{1}}的ID。 我的所有项目R.strings约为20项,我的arraylist已经过优化drawables,我将其转换为矢量绘图。但是当我滚动时它并不顺畅。我该怎么做才能优化它?

1 个答案:

答案 0 :(得分:1)

您需要直接使用资源访问您的drawable,而不是反射。

您应该将drawables放在相应的“drawables”文件夹中(drawable-xhdpi,drawable-xxhdpi等)。然后在您的对象中引用与每个drawable关联的int:

public class CatModel {
    public String txt,des;
    public int drawable;
}

其中drawable是你的一个drawable,比如

CatModel catModel = new CatModel();
catModel.drawable = R.drawable.my_drawable_1;

等等。

然后在您的适配器中使用它:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.cat_text.setText(objects_.get(position).txt);
    holder.cat_des.setText(objects_.get(position).des);
    holder.img.setImageResource(objects_.get(position).drawable);
}