获取 Cardview 背景颜色
get Cardview Background Color
我在 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 背景颜色?
您可以简单地初始化一个 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();
注意这个方法returns一个ColorStateList
而不是一个单一的颜色值
所以要获得单个颜色值,只需调用:
int backgroundColor = cardView.getCardBackgroundColor().getDefaultColor();
我在 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 背景颜色?
您可以简单地初始化一个 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();
注意这个方法returns一个ColorStateList
而不是一个单一的颜色值
所以要获得单个颜色值,只需调用:
int backgroundColor = cardView.getCardBackgroundColor().getDefaultColor();