setVisibility(GONE) view becomes invisible but still occupies space

This is an Android bug in my opinion, we just fix this issue doing this:

<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>

Just hide LinearLayout with id LAYOUT_TO_HIDE with Visible.GONE and then root FrameLayout will collapse its height giving you a "hidden" with non-blank-space header.


All replies in this thread are suggesting a new wrapper view, which comes at a cost. The correct way of hiding a view completely is to set margins to 0 while setting visibility to GONE. In this code sample, cardView is the view I am trying to hide. The direct parent of cardView is RecyclerView, that's why we are using RecyclerView.LayoutParams - remember to replace with the right layout params.

if (cardView.getVisibility() != GONE) {
    cardView.setVisibility(GONE);
    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) cardView.getLayoutParams();
    layoutParams.setMargins(0, 0, 0, 0);
    cardView.setLayoutParams(layoutParams);
}

set layout_width and layout_height to 0 where you want to hide item, by doing this

//if item's parent layout is LinearLayout, change according to your item xml
holder.itemView.setLayoutParams(new LinearLayout.LayoutParams(0,0));