CardView Padding/Spacing 因 API 级别而异

CardView Padding/Spacing Varies on Different API Level

我正在多个设备上测试我的应用程序并注意到使用 CardView 时,某些设备在每个 CardView 之间呈现间距。

我试图找出问题所在,看起来 API 23 不包含任何间距,而 API < 23 呈现某种 padding/spacing.

请注意,我已经尝试了 here 提出的解决方案,但没有奏效。它在 XML 中提出以下建议:

app:cardUseCompatPadding="true"

API 23

API < 23

问题是 api-21 及更高版本原生支持 CardView,而在 KitKat 及更早版本上,支持库 "faked" 支持它们。

我过去成功的做法是使用单独的布局文件,然后手动对它们进行像素推送,直到看起来正确为止。

例如,在 res/layout 中,你有这个 xml:

<android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:cardview="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/my_card"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_marginRight="0dip"
     android:layout_marginLeft="0dip"
     android:layout_marginTop="1dip"
     android:layout_marginBottom="1dip"
     cardview:cardBackgroundColor="@color/even_light_gray"
     android:foreground="@drawable/card_foreground"
     cardview:cardCornerRadius="1dp" >

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="8dp"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:paddingTop="4dp" >

        <!-- .......... -->

        </LinearLayout>
</android.support.v7.widget.CardView>

然后,在 res/layout-21 中,您的布局具有不同的边距和填充值:

<android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:cardview="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/my_card"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_marginRight="1dip"
     android:layout_marginLeft="1dip"
     android:layout_marginTop="4dip"
     android:layout_marginBottom="4dip"
     cardview:cardBackgroundColor="@color/even_light_gray"
     android:foreground="@drawable/card_foreground"
     cardview:cardCornerRadius="1dp" >

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="8dp"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="4dp" >

        <!-- .......... -->

        </LinearLayout>
</android.support.v7.widget.CardView>

我发现这个... 在 cardview attr 中使用它,
app:cardPreventCornerOverlap="false"
并在不同的 android os 版本
中使用它 app:cardMaxElevation="0dp" app:cardElevation="0dp"
在 pre-L 中,将它们设为 0dp,在 api21 或之后,将它们设为非零