karthik
karthik

Reputation: 47

get Cardview Background Color

I Set a Random Color for CardView In Android.

Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        holder.cardView.setBackgroundColor(color);

How To Get Cardview Background Color at Runtime Programmatically?

Upvotes: 3

Views: 2278

Answers (1)

0xA
0xA

Reputation: 1540

You can simply initialize a CardView and set an id:

as an example in your .xml file in res/layout:

<android.support.v7.widget.CardView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/CardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="10dp"
    app:cardCornerRadius="4dp"
    app:cardBackgroundColor="@color/cardview_dark_background"
    android:background="@color/cardview_dark_background">

and then initalize it in your Activity/Fragment so:

 CardView cardView = (CardView) findViewById(R.id.CardView);
 cardView.getCardBackgroundColor();

note that this method returns a ColorStateList rather than a single color value

so to get a single color value just call:

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

Upvotes: 6

Related Questions