RecyclerView layoutmanager for changing row and column span

后端 未结 2 470
执念已碎
执念已碎 2020-12-13 16:30

I am looking to create the following layout (red sqaures does not really have to be squares, a custom fixed height is also fine). The layout seems very simple yet I did not

2条回答
  •  青春惊慌失措
    2020-12-13 16:44

    A little bit late, but it might help everyone else...

    I was looking for the same and finally, after 2 days of googling I found a solution. Big thanks to Nick Butcher! His layout manager called SpannableGridLayoutManager is capable of doing this. In my case I was doing a pattern like your first two rows:

    Solution is easy:

    1. Download SpannableGridLayoutManager from here

    For some reason I had to change this line:

    while (availableSpace > 0 && lastVisiblePosition < lastItemPosition) {
    

    to

    while (lastVisiblePosition < lastItemPosition) {
    

    to got the manager working.

    2. Set SpannableGridLayoutManger to your RecyclerView

    In my case:

        SpannedGridLayoutManager manager = new SpannedGridLayoutManager(
                new SpannedGridLayoutManager.GridSpanLookup() {
                    @Override
                    public SpannedGridLayoutManager.SpanInfo getSpanInfo(int position) {
                        // Conditions for 2x2 items 
                        if (position % 6 == 0 || position % 6 == 4) {
                            return new SpannedGridLayoutManager.SpanInfo(2, 2);
                        } else {
                            return new SpannedGridLayoutManager.SpanInfo(1, 1);
                        }
                    }
                },
                3, // number of columns
                1f // how big is default item
        );
    

    Which gave me exactly what I wanted (numbers are position of item in adapter):

    EDIT: error with styleable Put those lines into attrs.xml

    
        
        
        
    
    

提交回复
热议问题