获取Cardview的背景色

3
我在Android中为CardView设置了随机颜色。
Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        holder.cardView.setBackgroundColor(color);

如何在运行时以编程方式获取CardView的背景颜色?

你可以用Color.rgb(...)替换Color.argb(255,...),如果alpha值始终为255,则无需使用Color.argb(...) - Omar Hemaia
1个回答

6
您可以简单地初始化一个CardView并设置id:
例如,在res/layout中的.xml文件中:
<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">

然后在您的 Activity/Fragment 中初始化它:

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

请注意,此方法返回一个ColorStateList而不是单个颜色值。因此,要获取单个颜色值,只需调用:
int backgroundColor = cardView.getCardBackgroundColor().getDefaultColor();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接