YuvrajsinhJadeja
YuvrajsinhJadeja

Reputation: 1422

setting a custom margin between view of a recyclerview

I am trying to make recyclerview in which I can put a custom margin on view item based on an id in android

I tried custome adapter with a different view which we can put in one recycler view but I need only one view and only want to do is put custom margin between view based on id.

if (category_detail.getId()==0){
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) rec_discount.getLayoutParams();
        marginLayoutParams.setMargins(0, 500, 0, 0);
        rec_discount.setLayoutParams(marginLayoutParams);


 }

enter image description here

Upvotes: 1

Views: 175

Answers (1)

Vikas Malhotra
Vikas Malhotra

Reputation: 131

You can use ItemDecoration to achieve this.

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;

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

    @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.getChildAdapterPosition(view) == 0) {
            outRect.top = space;
        }
    }
}

This will add a margin of "space" pixels on the left, right and bottom sides of all views in the recycler view. You can customize as per your requirements.

To use this class you can do this:

recyclerView.addItemDecoration(new SpacesItemDecoration(10));

Upvotes: 4

Related Questions