Search code examples
androidandroid-recyclerviewandroid-cardviewcardview

Want to add horizontal spacing between cards of CardView in android?


Want to add Spacing between the cards of CardView without using cardUseCompatPadding, How can i achieve that ?


Solution

  • Set Padding on rows so that all the items set spacing between each items

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#FFF"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    // here your views
    
    </LinearLayout>
    

    or, Use like this by java to saperate items

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());  
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
    

    Class

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

    }