Java Android-CardView背景始终为灰色

Java Android-CardView背景始终为灰色,java,android,background,android-cardview,Java,Android,Background,Android Cardview,我正在尝试以编程方式更改CardView颜色 这是我的CardView: <android.support.v7.widget.CardView android:id="@+id/createsub_card" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp"> 其中sub.getColor()在这

我正在尝试以编程方式更改CardView颜色

这是我的CardView:

<android.support.v7.widget.CardView
    android:id="@+id/createsub_card"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp">
其中
sub.getColor()
在这种特定情况下返回以下颜色:

<color name="color_black">#000000</color>
#000000
应该是漆黑一片。我的CardView仍然是这样的:


知道为什么会发生这种情况以及如何解决吗?

我假设问题是由sub.getColor()引起的。首先正确返回颜色代码

你可以试试这个

cardView.setCardBackgroundColor(Color.parseColor("#000000"));


问题是sub.getColor(),返回的是颜色id(R.color.color\u black)而不是颜色代码。请参阅下面的代码

sample.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.CardView
        android:id="@+id/createsub_card"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_margin="10dp">


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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Click"
        android:layout_below="@+id/createsub_card"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="13dp" />
</RelativeLayout>
错误方式:

private int getColorWrongWay()
{
    return mColor;
}
 private int getColorCrtWay()
{
    return getResources().getColor(mColor);
}
正确的方法:

private int getColorWrongWay()
{
    return mColor;
}
 private int getColorCrtWay()
{
    return getResources().getColor(mColor);
}
输出:


sub.getColor()
@IntelliJAmiya的问题您认为问题出在
sub.getColor()
?这是一个很好的标准制定者…请确保添加
Color.RED
而不是
sub.getColor()
你能把你从哪里得到颜色的类sub贴出来吗?我想你的sub.getColor()卡住了,你能用那种方法很乐意帮助@Daniele:)@IntelliJAmiya你写了一条评论他写了一个很好的答案。无论如何谢谢你的帮助
 private int getColorCrtWay()
{
    return getResources().getColor(mColor);
}