簡體   English   中英

如何從RecyclerView的ItemDecoration類訪問LayoutManager?

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

我找不到任何關於它的帖子...

我們有舊的RecyclerView.ItemDecoration代碼(摘自Suleiman的Mansonry Github項目 ):

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

我想根據RecyclerView中的當前LayoutManager設置mSpace (偏移/邊距)的條件。

例如:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM