Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility gone in recyclerview still occupies spaces?

Here is my current code. I want to hide a specific item on my recyclerview but when I use visibility.gone still occupies spaces on the recyclerview. I also tried all the possible solutions How to hide an item from Recycler View on a particular condition? Any help

  for(int j =0; j < minusList.size(); j++){
      int availableRooms =  minusList.get(j);

      if(norooms > availableRooms){ //norooms is the number of rooms wanted
      holder.itemView.setVisibility(View.GONE);
      mAdapter.notifyItemRemoved(position);
     }else{
      holder.rRoomsLeft.setText("Room available");
     }

}

Here is my XML

<android.support.v7.widget.RecyclerView
                android:id="@+id/listView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="false"
                android:focusableInTouchMode="false" />
like image 626
nani10 Avatar asked Mar 12 '19 07:03

nani10


2 Answers

instead of using holder.itemView.setVisibility(View.GONE);, use this:

  ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
  params.height = 0;
  holder.itemView.setLayoutParams(params);
like image 163
Hadi Ahmadi Avatar answered Nov 10 '22 15:11

Hadi Ahmadi


1.Why does it happen?

holder.itemView.setVisibility(View.GONE); This will not work in RecyclerView.

itemView is a child view in RecyclerView. Unlike the other ViewGroup (FrameLayout,etc), RecyclerView ignores childen's visibility during layout process.

2.How to solve it?

Option1 Use a regular view group such as FrameLayout to wrap your real layout, and hide your real layout: findViewById(R.id.layout_to_hide).setVisibility(View.GONE)

<FrameLayout android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout android:id="@+id/layout_to_hide"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content">
         //Put here your views
    </LinearLayout>
</FrameLayout>

Option2 Change the itemView’s heigh to 0 so we can't see it

holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0));

Option3 If this item shouldn't be in List, then simply don't let it in adapter data, or remove it.

3.Learn more

1. Why the other view group such as FrameLayout works fine with children's visibibilty?

They don't compute the child's layout params if it's GONE

enter image description here

enter image description here

enter image description here

2. Why RecyclerView doesn't?

RecyclerView still compute the child's layout params if it's GONE so it still occupies spaces.

recycler view

like image 44
Bruce Lin Avatar answered Nov 10 '22 14:11

Bruce Lin