得到Cardview背景颜色

问题描述 投票:2回答:1

我设置随机颜色CardView在Android中。

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

如何在运行时编程方式获得Cardview背景颜色?

android background-color android-cardview
1个回答
2
投票

你可以简单地初始化CardView和设置ID:

如在RES /布局的.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">

然后初始化它在你的活动/片段这样:

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

注意,这个方法返回一个ColorStateList而不是单一的颜色值

因此要获得一个单一的颜色值只要致电:

int backgroundColor = cardView.getCardBackgroundColor().getDefaultColor();
© www.soinside.com 2019 - 2024. All rights reserved.