Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

android - RecyclerView layoutmanager for changing row and column span

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 find a layout manager which suits my needs.

wat i want

I tried the StaggeredGridLayoutManager but this only allows to set the span of either the column or the row, not both.

Is there floating around a custom layout manager which is able to do this? I have looked at TwoWayView but changing height seems to be problematic and the library is not being maintained.

Anyone having this problem and solved it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here

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

enter image description here

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

<declare-styleable name="SpannedGridLayoutManager">
    <attr name="android:orientation" />
    <attr name="spanCount" />
    <attr name="aspectRatio" format="string" />
</declare-styleable>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...