CardView背景颜色总是白色

Ish*_*aan 109 android android-cardview android-recyclerview

我正在使用RecyclerView和GridLayoutManager,我将每个项目都作为CardView.

不幸的是,这里的CardView似乎没有改变它的背景颜色.我尝试了布局和编程方式,但我似乎没有尝试过什么似乎工作.

我一直在苦苦挣扎.如果有人可以帮我解决这个问题,我感激不尽.

Lea*_*ira 275

如果要更改卡背景颜色,请使用:

app:cardBackgroundColor="@somecolor"
Run Code Online (Sandbox Code Playgroud)

像这样:

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@color/white">

</android.support.v7.widget.CardView>
Run Code Online (Sandbox Code Playgroud)

编辑: 正如@imposible指出的那样,你需要包括

xmlns:app="http://schemas.android.com/apk/res-auto"
Run Code Online (Sandbox Code Playgroud)

在您的根XML标记中,以便创建此代码段功能

  • 谢谢你的回答,欣赏它. (2认同)
  • 在那里,你的布局文件中包含xmlns:app ="http://schemas.android.com/apk/res-auto". (2认同)

Non*_*hoi 31

您可以使用XML或以编程方式执行此操作:

在XML中:

card_view:cardBackgroundColor="@android:color/red"
Run Code Online (Sandbox Code Playgroud)

编程方式:

cardView.setCardBackgroundColor(Color.RED);
Run Code Online (Sandbox Code Playgroud)


小智 9

用于XML 的Kotlin

app:cardBackgroundColor="@android:color/red"

代码

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

  • 谢谢。我以前使用过 card.setCardBackgroundColor(R.color.bla) ,这导致了非常奇怪的结果。通过 ContextCompat 获取颜色对我来说很有效。 (2认同)

yoA*_*ex5 5

XML 代码

<android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="5dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="#e4bfef"
        app:cardElevation="4dp"
        app:cardMaxElevation="6dp" />
Run Code Online (Sandbox Code Playgroud)

从代码

CardView card = findViewById(R.id.card_view_top);
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));
Run Code Online (Sandbox Code Playgroud)