简体   繁体   中英

How to access the LayoutManager from the RecyclerView's ItemDecoration class?

I haven't been able to find any post about it...

We have the good old RecyclerView.ItemDecoration code (taken from Suleiman's Mansonry Github project ):

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private final int mSpace;

    public SpacesItemDecoration(int space) {
        this.mSpace = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = mSpace;
        outRect.right = mSpace;
        outRect.bottom = mSpace;

        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildAdapterPosition(view) == 0)
            outRect.top = mSpace;
    }
}

I want to have a condition that sets mSpace (offset/margin) depending on the current LayoutManager in the RecyclerView .

For example:

if(/* LayoutManager is LinearLayoutManager*/){
   //Set larger margin
}else{
   //Set lower margin
}

So... as I was re-reading the question to check if anything was missing, and I realized that you actually get a RecyclerView reference (parent) as an argument of getItemOffsets() .

So you can just call parent.getLayoutManager() from inside the function.

Example:

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

    if (parent.getLayoutManager() instanceof LinearLayoutManager){
        margin = 2;
    }else if (parent.getLayoutManager() instanceof StaggeredGridLayoutManager){
        margin = 1;
    }else{
        margin = 0;
    }

    //Do magic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM