recyclerview loads an item, setting the spacing between the top and bottom of a particular item

I don't know how, I don't want to learn any more recently, I start playing together again, and I don't have anything useful with unknown fantasies.Today I put down the things I forgot. It's not good to stop flipping through other people's blogs when I use them.

Set the spacing for the specified item,

Write a class on the first page

pubulic class RecyclerView  extends ReyclerView.ItemDecoration{

//Define local variables
private int space;


//Create Construct
public RecyclerView(int space){
//initialize variable
this.space=space;
}
//override method
getitemoffsets

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

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


}

LinearLayoutManager written above

 

Here's how GridLayoutManager or StaggeredGridLayoutManager sets the Item spacing

 

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

   private int spanCount; //Number of columns
   private int spacing; //interval
   private boolean includeEdge; //Include edges or not

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
       
       //Here's the key, depending on how many columns you have
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

call

int spanCount = 3; // 3 columns int spacing = 50; // 50px boolean includeEdge = false;

mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));


 

Added by jaslife on Thu, 30 Jan 2020 18:35:46 +0200