没有获取 CardView 当前背景颜色的方法

There is no method to get the current background color of CardView

没有获取CardView当前背景颜色的方法。有一种设置背景的方法

cardView.setCardBackgroundColor(color);

我想要这样的东西:

cardView.getCardBackgroundColor();

这真的很有帮助。

您应该在 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_width="match_parent"
android:layout_height="wrap_content">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible">

</RelativeLayout>

在这种情况下,尝试从RelativeLayout设置和获取。

gradle 有问题。我使用的是与其他一些库捆绑在一起的旧版本 CardView。通过添加以下行修复:

compile 'com.android.support:cardview-v7:24.2.1'

看起来 getCardBackgroundColor() 方法确实已添加到 CardView,但在相当新的版本中,因此请确保您的支持库版本是最新的。

请注意,此方法 returns 一个 ColorStateList 而不是单个颜色值。调用 getDefaultColor() 会给你正常的背景颜色。

int backgroundColor = cardView.getCardBackgroundColor().getDefaultColor();