gpt4 book ai didi

java - 如何从RecyclerView的ItemDecoration类访问LayoutManager?

转载 作者:太空宇宙 更新时间:2023-11-04 12:58:48 24 4
gpt4 key购买 nike

我没找到任何相关的帖子...

我们有旧的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;
}
}

我想要一个根据当前 LayoutManager 设置 mSpace (偏移/边距)的条件在 RecyclerView .

例如:

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

最佳答案

所以...当我重新阅读这个问题以检查是否缺少任何内容时,我意识到您实际上获得了一个 RecyclerView 引用(父级)作为 getItemOffsets() 的参数.

因此,您只需从函数内部调用 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
}

关于java - 如何从RecyclerView的ItemDecoration类访问LayoutManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35121686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com