Android RecyclerView, recycling is not working properly… here is a solution to the problem.
Android RecyclerView, recycling is not working properly
I
have a RecyclerView
that I am using. I’ve used RecyclerView
before but have never encountered this issue.
When I scroll up and down, some items disappear and some disappear again at the bottom.
Code:
ViewHolder
:
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txt;
public ViewHolder(View view) {
super(view);
txt = (TextView) view.findViewById(R.id.txt);
}
}
Adapter
:
public class MyAdapter extends RecyclerView.Adapter<ViewHolder> {
private final Activity activity;
private final ArrayList<HashMap<String, String>> mItems;
public MyAdapter (Activity activity, ArrayList<HashMap<String, String>> mItems) {
this.activity = activity;
this.mItems= mItems;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return new ViewHolder(LayoutInflater.from(activity).inflate(R.layout.items, viewGroup, false));
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
HashMap<String, String> item = mItems.get(position);
String info = item.get("info ");
if (info!= null) {
viewHolder.txt.setText(info);
} else {
viewHolder.txt.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return (null != mItems? mItems.size() : 0);
}
}
Solution
onBindViewHolder
reuses View, so assume that the first time onBindViewHolder()
is called, info
is null
. This causes the row to have the visibility of View.SINGLE.
When onBindViewHolder
is called again to bind (bind) a new line, the view for that row remains View.GONE
– there are no resets between bound (bind) lines.
So your if statement should reset the state completely:
if (info!= null) {
viewHolder.txt.setText(info);
viewHolder.txt.setVisibility(View.VISIBLE);
} else {
viewHolder.txt.setVisibility(View.GONE);
}
This will ensure that the visibility of each row is set correctly.