Android RecyclerView与CardView:卡片之间的边距

4

我目前正在构建我的第一个Android应用程序,并使用来自Material Design的RecyclerView和Cards。然而,我希望在卡片和屏幕边缘之间以及卡片之间有相同的边距。根据我设置边距的方式,我会遇到不同的问题:

变体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>

这导致卡片之间的空间是卡片和屏幕边缘之间的两倍。 变体2:
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="0dp"

这是我的当前实现。它修复了卡片之间过宽的问题,但代价是列表底部没有间距。也就是说,如果我滚动到底部,卡片的下沿将与屏幕的下沿对齐。我也想在那里有一个间距。
第三个选项是将RecyclerView放置在额外的布局中,并使用布局将边缘设置为边缘。这样做的问题是,如果您滚动到列表的顶部或底部并继续拉动,出现的波浪形“超滚动区域”仅出现在RecyclerView内,而不延伸到屏幕的边缘。因此,它看起来有点hacky。 为了澄清,我附加了一张截图,在RecyclerView上使用4dp填充 感谢您的帮助 ;)

你可以指定一个item_layout用于在recycler view中使用。 - Abdulwahid
2个回答

3
尝试这个。要应用卡片视图布局,请使用以下内容。
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"

如何为RecyclerView添加内边距

android:paddingTop="4dp"
android:paddingBottom="4dp"

谢谢!我认为这属于第三种变体。如描述的那样,这会导致“超滚动区域”和状态栏/屏幕下沿之间存在间隙。我添加了一张截图以便澄清。 - Johannes Döllinger
@JohannesDöllinger 为了避免间隙,请将clipToPadding设置为“false”以针对Recyclerview。 - Nabeel

1

只选其一,不要两者都添加

android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"

这将复制数值。
添加marginBottom,就足够了。
android:layout_marginBottom="8dp"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接