EngineSense
EngineSense

Reputation: 3616

CardView setCardBackground Color not working in code

I've been trying to solve this for, more than 3 hours.

JellyBeab 4.1.6

I have a layout which contains card view and i'm setting the setCardbackground color programatically.

What i've tried so far is

    CARD = (CardView) view.findViewById(R.id.cardMechInfo);
    int[] array = new int[4];
    array[0] = activity.getResources().getColor(R.color.LightSkyBlue);
    array[1] = activity.getResources().getColor(R.color.Teal200);
    array[2] = activity.getResources().getColor(R.color.LightGrey);
    array[3] = activity.getResources().getColor(R.color.LightCoral);
    int randomColor = new Random().nextInt(array.length);
    CARD.setCardBackgroundColor(randomColor);

Layout file hierarchy like this.

<android.support.v7.widget.CardView
    android:id="@+id/cardMechInfo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_marginTop="5dp"
    android:layout_weight="1"
    FAB:cardCornerRadius="5dp"
    android:gravity="center_vertical|center_horizontal"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal"
        > ..........

The problem is when random color sets, the color seems to be appearing at the end of the card like a thinned line.

Did anybody faced problem like this. Please suggest how to solve this.

Thanks, Pusp

Upvotes: 0

Views: 822

Answers (3)

EngineSense
EngineSense

Reputation: 3616

SOLUTION

It seems pskink pointed out me that the random value returns some surprise values, As he suggested me to use this :

int randomColor = array[new Random().nextInt(array.length)];

Then it works on the cardView.

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

The LinearLayout inside the card has width and height of match_parent, so it is obscuring most of the card's background.

Upvotes: 1

frogatto
frogatto

Reputation: 29285

Seems you've got a LinearLayout inside that CardView and have 5dp margins around it.

If your LinearLayout has a non-transparent background, you will no longer see background of the CardView. So, you could set background of that LinearLayout to transparent or semi-transparent, then you can see CardView's background.

Fully transparent:

android:background="@android:color/transparent"

For semi-transparent, you could set it's alpha channel.

Upvotes: 0

Related Questions