How to remove the space occupied by hidden items in a Recyclerview?

15 Views Asked by At

I have created a Recyclerview in which the functionality is on option selection of 1st question I have to show/hide the child question. But after hiding the item in adapter it is leaving the span space occupied by the item.

I have tried Item Decoration but it is not working for me

int spacing = 16; // Change this to your desired spacing
yourRecyclerView.addItemDecoration(new CustomItemDecoration(spacing));

public class CustomItemDecoration extends RecyclerView.ItemDecoration {
    private int spacing;

    public CustomItemDecoration(int spacing) {
        this.spacing = spacing;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);

        // Check visibility and adjust spacing
        if (!yourAdapter.isVisible(position)) {
            outRect.set(0, 0, 0, 0); // Set zero spacing for hidden items
        } else {
            outRect.set(spacing, spacing, spacing, spacing);
        }
    }
}

Also I have tried GridLayoutManager span size lookup but that also didn't work.

GridLayoutManager layoutManager = new GridLayoutManager(context, spanCount);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        // Adjust span size based on visibility
        return yourAdapter.isVisible(position) ? 1 : spanCount;
    }
});

yourRecyclerView.setLayoutManager(layoutManager);
0

There are 0 best solutions below