如何从RecyclerView的ItemDecoration类访问LayoutManager?

时间:2016-02-01 01:20:32

标签: java android android-layout android-recyclerview

我找不到关于它的任何帖子......

我们有一个很好的旧RecyclerView.ItemDecoration代码(取自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;
    }
}

我希望条件设置mSpace(偏移量/保证金),具体取决于LayoutManager中的当前RecyclerView

例如:

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

1 个答案:

答案 0 :(得分:0)

所以...因为我正在重新阅读问题以检查是否有任何遗漏,我意识到你实际上得到了一个RecyclerView引用(父)作为{{3}的参数}。

所以你可以从函数内部调用parent.getLayoutManager()

示例:

@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
}