CardView 异常行为

CardView Strange Behaviour

我有一个简单的 CardView 布局

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cv_tag"
android:layout_width="wrap_content"
android:layout_height="@dimen/tag_height"
android:layout_margin="4dp"
android:clickable="true"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">

<FrameLayout
    android:id="@+id/fl_selection_indicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="8dp"
        android:textAppearance="@style/PrimaryWhiteText.Tiny"
        tools:text="Hard"/>

</FrameLayout>

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

它的呈现方式与我预期的不一样。看起来系统将此布局包装到具有高度和白色背景的 FrameLayout 中。有趣的是,如果我自己将此布局包装到 FrameLayout 中,高度消失但白色背景仍然存在(框架布局的背景不是 CardView)

如何去除高度和白色背景,为什么会这样?

提前致谢!

可能是API 21 实施前的一个怪癖。

与此同时,您可能完全不需要 CardView。考虑使用 DrawableResource。

参考How do I set the rounded corner radius of a color drawable using xml?

旧答案:

默认情况下,CardView 具有根据您的主题设置的背景颜色。 这是免除样式

<color name="cardview_dark_background">#FF424242</color>
<color name="cardview_light_background">#FFFFFFFF</color>

并且从视图的初始化开始

if (a.hasValue(R.styleable.CardView_cardBackgroundColor)) {
            backgroundColor = a.getColorStateList(R.styleable.CardView_cardBackgroundColor);
} else {
     // There isn't one set, so we'll compute one based on the theme
     final TypedArray aa = getContext().obtainStyledAttributes(COLOR_BACKGROUND_ATTR);
     final int themeColorBackground = aa.getColor(0, 0);
     aa.recycle();

     // If the theme colorBackground is light, use our own light color, otherwise dark
     final float[] hsv = new float[3];
     Color.colorToHSV(themeColorBackground, hsv);
     backgroundColor = ColorStateList.valueOf(hsv[2] > 0.5f
                    ? getResources().getColor(R.color.cardview_light_background)
                    : getResources().getColor(R.color.cardview_dark_background));
 }

要更改颜色,请使用 app:cardBackgroundColor 属性

原答案是

我的 latout 用于自定义视图,当我添加 setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));它的构造者海拔和白色背景已经消失。