Amir_P Amir_P - 7 months ago 26
Java Question

Items of recyclerview confused

In my

onBindViewHolder
of my
RecyclerView.Adapter<SearchAdapter.ViewHolder>
if user clicks a button visible. But when I'm scrolling recyclerview some other items button is visible too. why is this happening?

this is my code:

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
viewHolder.card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (viewHolder.content_layout.getVisibility() == View.VISIBLE) {
viewHolder.content_layout.setVisibility(View.GONE);
viewHolder.address.setMaxLines(2);
viewHolder.attribute.setMaxLines(2);
} else {
viewHolder.content_layout.setVisibility(View.VISIBLE);
viewHolder.address.setMaxLines(8);
viewHolder.attribute.setMaxLines(8);
}
}
});
...
}

Answer

Once you start scrolling down the list your views get recycled. This means a previously inflated ViewHolder (some that gets created in onCreateViewHolder) is reused.
So what you have to do is to remember the clicked positions (e.g. via a SparseBooleanArray) and check in onBindViewHolder whether the view should be visible (previously clicked) or not.

You can find a basic usage example of the SparseBooleanArray in this StackOverflow post

Comments