Search code examples
androidandroid-recyclerviewinvisible

How to hide RecyclerView items


I want to hide some of RecyclerView items as shown in the image. When view all is clicked, the layout should expand and remaining items should be visible.

RecyclerView

There are total of 12 items in the RecyclerView. One row should be hidden.

What I tried was making the items invisible at the beginning and set them to visible when view all is clicked by calling a method.

In the adapter I tried this

@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int i) {
if(i >= 8)
    {
        holder.productName.setVisibility(View.INVISIBLE);
        holder.product_image.setVisibility(View.INVISIBLE);
    }
}
public void viewAll() {
    //unable to create holder object here
    if(holder.productName.getVisibility() == View.INVISIBLE)
    {
        holder.productName.setVisibility(View.INVISIBLE);
        holder.product_image.setVisibility(View.INVISIBLE);
    }

}

But I am unable to create ViewHolder instance in view all method. And also empty spaces are being created where the items are in invisible. Any other techniques which you think is better?


Solution

  • Add variable int maxCount = 8 and change code to this:

        @Override
        public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int i) {
            if (i >= maxCount) {
                holder.productName.setVisibility(View.GONE);
                holder.product_image.setVisibility(View.GONE);
            }
        }
    

    And change maxCount on View All click;

        public void viewAll() {
            maxCount = 12;
            notifyDataSetChanged();
        }