Search code examples
androidandroid-layoutandroid-recyclerviewandroid-gridlayout

LinearLayout span after rotation


I have a RecyclerView using a GridLayout. The RecyclerView has heterogeneous layouts (I followed this guide link) with the difference that I have only on top of the recyclerView a textView showing some data. It works fine but when I rotate the screen, and the gridlayout is set with two or more spans, the textView is shown on the first span only but I want that the span will take the entire width of the screen regardless the number of spans.

Should I use a tableLayout for that?


Solution

  • All you need to do is set a custom SpanSizeLookup on your GridLayoutManager.

        final int numSpans = ...
    
        // Create a grid layout with numSpans columns
        GridLayoutManager layoutManager = new GridLayoutManager(this, numSpans);
    
        // Create a custom SpanSizeLookup where the first item spans all columns
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? numSpans : 1;
            }
        });