Search code examples
javaandroidandroid-studiomultiple-columnscardview

Android Studio CardView with two columns that have equal width


I am trying to display in a cardview two elements on each row ( two columns ). However, they are not centered in the cardview. click here to see how the cardview displays items

Here is the code in the xml.:

 <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFDB78"
            android:layout_below="@+id/LinearLayoutCateg"
            android:layout_above="@+id/menu"
            android:id="@+id/currentCategoryRecyclerView"/>

I create a new GridLayoutManager in the Main activity, programatically, like this:

 recyclerView.setLayoutManager(new GridLayoutManager(CategoryListActivity.this,2));
        recyclerView.setAdapter(categoryRecycler);

The cardview is in a Relative Layout that has the "android:gravity="center" property, if that matters. I am not sure what I am missing.


Solution

  • I have the same problem as you, I found the RecyclerView.ItemDecoration class for RecyclerView Spacing.

    public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
    
    private int mItemOffset;
    
    public ItemOffsetDecoration(int itemOffset) {
        mItemOffset = itemOffset;
    }
    
    public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {
        this(context.getResources().getDimensionPixelSize(itemOffsetId));
    }
    
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset);
    }
    

    }

    Add ItemOffsetDecoration to your RecyclerView.
    Item offset value should be half size of the actual value you want to add a space between items.

     mRecyclerView.setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS);
    ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.dimen.item_offset);
    mRecyclerView.addItemDecoration(itemDecoration);
    

    Also, set item offset value as padding for its RecyclerView, and specify android:clipToPadding=false.

    <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:padding="@dimen/item_offset"/>    <!--Give a desired size-->
    

    refer