解决这个问题的方法是通过使用“重用视图”来优化您的RecyclerView适配器。具体来说,您可以检查您的适配器中每个ViewHolder的实现,以确保您在必要时正确地使用缓存视图。
以下是一个例子,展示了如何在共享单个ViewStub实例的情况下使用“策略”来适当重用视图:
public class MyAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private final ViewStub mCachedViewStub;
private int mLastPosition = -1;
private final RecyclingLayoutManager mLayoutManager;
private List mData = new ArrayList<>();
public MyAdapter(Context context, RecyclerView recyclerView) {
mInflater = LayoutInflater.from(context);
mCachedViewStub = new ViewStub(context);
mLayoutManager = new RecyclingLayoutManager(context);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(this);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
final View view = mCachedViewStub.inflate();
final ViewHolder holder = new ViewHolder(view);
mLayoutManager.registerViewHolder(holder);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final MyObject item = mData.get(position);
if (item != null) {
holder.bind(item);
holder.itemView.setVisibility(View.VISIBLE);
mLastPosition = position;
} else {
holder.itemView.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return mData.size();
}
public void swapData(List data) {
mData = data != null ? new ArrayList<>(data) : new ArrayList<>();
notifyDataSetChanged();
}
static class RecyclingLayoutManager extends LinearLayoutManager {
private final SparseArray mViewHolders = new SparseArray<>();
RecyclingLayoutManager(Context context) {
super(context);
}
void registerViewHolder(MyAdapter.ViewHolder holder) {
mViewHolders.append(holder.hashCode(), holder);
}
@NonNull
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new MyLayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new MyLayoutParams(c, attrs);
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
return new MyLayoutParams(lp);
}
@Override