没有方法可以获得CardView的当前背景颜色

时间:2016-09-18 09:16:00

标签: android android-cardview

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

cardView.setCardBackgroundColor(color);

我想要像:

cardView.getCardBackgroundColor();

这将非常有用。

3 个答案:

答案 0 :(得分:5)

看起来getCardBackgroundColor()方法确实已添加到CardView,但在最新版本中,所以只需确保您的支持库版本是最新的。

请注意,此方法返回ColorStateList而不是单个颜色值。在其上调用getDefaultColor()将为您提供正常的背景颜色。

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

答案 1 :(得分:0)

您应该在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获取。

答案 2 :(得分:0)

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

compile 'com.android.support:cardview-v7:24.2.1'
相关问题