Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Items of RecyclerView are not showing correctly

In my onBindViewHolder of my RecyclerView.Adapter<SearchAdapter.ViewHolder> when user clicks on cardview a button becomes visible. But when I'm scrolling recyclerview some other items buttons are shown as 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);
            }
        }
    });
    ...
}
like image 535
Amir_P Avatar asked Apr 24 '16 14:04

Amir_P


People also ask

What is ViewHolder in RecyclerView?

A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results. While LayoutParams belong to the LayoutManager , ViewHolders belong to the adapter.

Is there an addHeaderView equivalent for RecyclerView?

addHeaderView() but you can achieve this by adding a type to your adapter for header. everything seems to be OK and it should work, but however make the recycler view MATCH_PARENT see if anything changes. also if its possible make the recycler view the root of that layout (its good for performance).


1 Answers

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

like image 54
reVerse Avatar answered Oct 16 '22 17:10

reVerse