How to determine column position in staggered grid layout manager
Asked Answered
M

2

23

I’m using a staggered recycler view layout for a list of photos. I want the spacing on the sides to be zero while still having space between the two columns. I’m using an item decoration sub class to get the spacing seen in the attached photo. I know I have control over the left and right spacing but the problem is that I never know which column the photo is in. It seems like the staggered layout manager does some of its own reordering. I've tried using getChildAdapterPosition but it seems to return the position in the data source array and not the actual position of the photo in the layout. Any idea how I should approach this? enter image description here

Milt answered 3/2, 2016 at 21:48 Comment(2)
That's what I'm also currently trying to figure out. The manager positions the views depending on their sizes, and you will never be sure that for example odd positions will be on the left and even positions will be on the right. That's how I tried to solve it in my item decorator, by checking position % 2 == 0 and then setting the rect.left margin...but it's not working like that since in some cases the item with position 6 can be on the right and sometimes on the left.Athens
Don't have the rep to comment on @Vasilisfoo's answer. Warning to those using getSpanIndex(): if you have previously setGapStrategy() to GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS then your span index will often return wrong values because the items get moved around after the span index has been set.Silicle
A
40

I managed to get it working. In my case, I don't need any borders on the left or right edges of the screen. I just need borders in the middle and bottom. The solution is to get the layout parameters of the view that are of type StaggeredGridLayoutManager.LayoutParams. In those parameters you can get the spanIndex that tells you on which index the view is. So if you have a spanCount of 2, the left view will have a spanIndex of 0 and the right view will have a spanIndex of 1.

Here is my code, maybe it help you.

public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

    public SpaceItemDecoration(int space) {
        this.space = space;
    }


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

        StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
        int spanIndex = lp.getSpanIndex();

        if (position > 0) {
            if (spanIndex == 1) {
                outRect.left = space;
            } else {
                outRect.right = space;
            }

            outRect.bottom = space * 2;
        }
    }
}

In my case, firstly I have to get the position, since on the index 0 I have a header View, which doesn't have any borders. After that, I get the span index and depending on it I set the borders that I need on that View. And finally I set the bottom border on every View.

Athens answered 5/2, 2016 at 14:29 Comment(2)
Thank you, I have been trying to hack this for my layout, which has one header view type, sub header view type and item view type. This is really elegant solution and works also with regular GridLayoutManager.Storeroom
Do you have a working example of this code? I tried in my project, for some reasons I don't understand, the spanIndex is always 0. It seems StaggeredGridLayoutManager call getItemOffsets before it decide which span the child view belongs to.Sumac
D
4

so the one solution I was able to use was with an item decorator but it definitely is a little weird/hacky feeling.

Basically you'll adjust the outer rectangle of the item based on its column position (or something similar). My understanding is that the outer rectangle is more or less the spacing you want to change. Give the code below a try, obviously you'll need to make your own adjustments and logic to 'calculate' which column the item is on but this should be enough to figure it out, hopefully:

recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int left = outRect.left;
            int right = outRect.right;
            int top = outRect.top;
            int bottom = outRect.bottom;
            int idx = parent.getChildPosition(view);
            int perRow = gridLayoutManager.getSpanCount();

            int adj = blahh... // some adjustment

            if (idx < itemsPerRow) {
                // on first row, adjust top if needed
            }

           if(idx % perRow == 0){
                // on first column, adjust. Left magically adjusts bottom, so adjust it too...
                left += adj;
                bottom -= adj;
           }

           if(idx % itemsPerRow == perRow - 1){
               // on last column, adjust. Right magically adjusts bottom, so adjust it too...
               right += adjustment;
               bottom -= adjustment;
           }

            outRect.set(left, top, right, bottom);
        }
    });

Again this is hacky and takes some trial and error to get right.

Another solution I have tried with some success is to define different views for the different columns. In your case the columns would have views with different, negative margins, on the left and right to get the effect you want.

As a side note, I assume you are using an elevation on the card view. One thing I've noticed is that if the card view does NOT have elevation and instead you handle it yourself (yeah, i know, isn't the point to not handle elevation yourself) much of this difficulty goes away and things start to behave, likely because of the elevation/shadow calculations. But anyway... Hope this is at least somewhat helpful...

Directory answered 5/2, 2016 at 4:7 Comment(2)
Hey, where's itemsPerRowinstantiated? ThanksLamellar
Helped me to get column and row numbersCray

© 2022 - 2024 — McMap. All rights reserved.