Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android RecyclerView with CardView: Margins between cards

I am currently building my first Android app and I am using a RecyclerView with Cards from Material Design. However, I would like to have the same margins between the cards and the edge of the screen and between the cards. Depending on how I set the margins, I get different problems:

Variant 1:

<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    app:cardElevation="2dp"
    app:cardUseCompatPadding="false">

...

</com.google.android.material.card.MaterialCardView>

This leads to twice as much space between the cards than between the cards and the edge of the screen.

Variant 2:

android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="0dp"

This is my current implementation. It fixes the wider space between the cards but at the cost of having no margin at the bottom of the list. I.e. if I scroll all the way to the bottom, the lower edge of the card lines up with the lower edge of the screen. I would also like to have a margin there.

Variant 3: The third option I tried was putting the RecyclerView inside an extra layout and used the layout to set the margins to the edges of the screen. This has the problem that if you scroll all the way to the top or bottom of the list and pull further, the appearing wavy "overscroll areas" do only appear within the RecyclerView and do not extend up to the edges of the screen. So it also looks a bit hacky. For clarification I attached a screenshot using a 4dp padding on the RecyclerView

Thanks for helping me out ;)

like image 949
Johannes Döllinger Avatar asked Oct 30 '25 06:10

Johannes Döllinger


1 Answers

Try this .To card view layout apply these

android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"

And to recyclerview add padding

android:paddingTop="4dp"
android:paddingBottom="4dp"
like image 128
Sahil Goyal Avatar answered Nov 01 '25 21:11

Sahil Goyal