为什么Lollipop上的CardViews之间没有空间?

时间:2014-11-20 09:11:22

标签: android android-cardview

我尝试使用CardView并且它在5.0以下工作得很好,但在棒棒糖上看起来很奇怪。

enter image description here

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<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="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<android.support.v7.widget.CardView android:layout_width="match_parent"
    android:layout_height="200dp">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="card1"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView android:layout_width="match_parent"
    android:layout_height="200dp">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="card2"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</android.support.v7.widget.CardView>
</LinearLayout>

当我使用RecyclerView时遇到同样的问题,如果它在Lollipop上运行,我是否需要添加一些内容?

4 个答案:

答案 0 :(得分:201)

CardView

上设置此项
app:cardUseCompatPadding="true"

来自文档:

  

在API v21 +中添加填充也可以使用相同的测量值   以前的版本。

答案 1 :(得分:29)

在您的cardview内使用以下两个标签:

app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true"

答案 2 :(得分:12)

第一张图片是卡片视图的预期行为。当卡片有高度时,阴影落在底层。在前棒棒糖装置中,通过添加填充来进行提升。所以棒棒糖前设备的卡片视图周围会有一个填充物。

  

在L之前,CardView会在其内容中添加填充并绘制阴影   那个地区。此填充量等于maxCardElevation +(1 -   cos45)*两侧的cornerRadius和maxCardElevation * 1.5 +(1 -   cos45)* cornerRadius在顶部和底部。

答案 3 :(得分:5)

您必须将app:cardUseCompatPadding="true"添加到Cardview。但只是添加它可能会给你一个错误。为避免该错误,您还必须将xmlns:app="http://schemas.android.com/apk/res-auto"添加到CardView

例如,

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:cardUseCompatPadding="true">

    // Other views here

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

有些会添加card_view:cardUseCompatPadding="true"xmlns:card_view="http://schemas.android.com/apk/res-auto",而不是上面提到的那些。两种方式都是正确的。

如果您想了解有关XML(Android)中 app 的更多信息,请仔细阅读answer

虽然之前的答案可以解决问题,但他们没有解释每个属性的作用。所以更有帮助回答寻求者,

cardPreventCornerOverlap属性在v20和之前为CardView添加了填充,以防止卡内容和圆角之间的交叉。

cardUseCompatPadding属性在API v21 +中添加了填充,以便与以前的版本具有相同的度量。