developer tip

프로그래밍 방식으로 CardView의 배경색 변경

optionbox 2020. 8. 2. 18:22
반응형

프로그래밍 방식으로 CardView의 배경색 변경


CardView는 속성이 card_view:cardBackgroundColor배경 색상을 정의 할 수 있습니다. 이 속성은 잘 작동합니다.

동시에 색상을 동적으로 변경하는 방법은 없습니다.

방금 다음과 같은 솔루션을 시도했습니다.

mCardView.setBackgroundColor(...);

또는 cardView 내부의 레이아웃 사용

   <android.support.v7.widget.CardView>
        <LinearLayout
            android:id="@+id/inside_layout">
    </android.support.v7.widget.CardView>  

 View insideLayout = mCardView.findViewById(R.id.inside_layout);
 cardLayout.setBackgroundColor(XXXX);

카드에 cardCornerRadius가 있기 때문에 이러한 솔루션이 작동하지 않습니다.


당신이 찾고있는 것은 :

CardView card = ...
card.setCardBackgroundColor(color);

XML에서

 card_view:cardBackgroundColor="@android:color/white"

업데이트 : XML

app:cardBackgroundColor="@android:color/white"

card_view : cardBackgroundColor 속성을 사용하십시오.

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

이것을 XML로 사용할 수 있습니다

card_view:cardBackgroundColor="@android:color/white"

또는 이것은 자바에서

cardView.setCardBackgroundColor(Color.WHITE);

이 코드를 사용하여 프로그래밍 방식으로 설정했습니다.

card.setCardBackgroundColor(color);

또는 XML에서는 다음 코드를 사용할 수 있습니다.

card_view:cardBackgroundColor="@android:color/white"

initialize메소드에 설정된 방식은 다음 RoundRectDrawable과 같이 protected 클래스를 사용합니다 .

RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);

예쁘지는 않지만 클래스를 확장 할 수 있습니다. 다음과 같은 것 :

package android.support.v7.widget;

public class MyRoundRectDrawable extends RoundRectDrawable {

    public MyRoundRectDrawable(int backgroundColor, float radius) {
        super(backgroundColor, radius);
    }

}

그때:

final MyRoundRectDrawable backgroundDrawable = new MyRoundRectDrawable(bgColor,
            mCardView.getRadius());
mCardView.setBackgroundDrawable(backgroundDrawable);

편집하다

이것은 <API 21에 대한 그림자를 제공하지 않으므로와 동일한 작업을 수행해야합니다 RoundRectDrawableWithShadow.

더 좋은 방법은 없습니다.


프로그래밍 방식이 아니기 때문에 위젯에 대한 스타일을 설정하는 것이 가장 좋으며 CardViewXML을 깔끔하게 유지하는 스타일을 만들기 위해이 작업을 수행 할 수 있습니다 .

<style name="MyCardViewStyle" parent="CardView">
    <!-- Card background color -->
    <item name="cardBackgroundColor">@android:color/white</item>
    <!-- Ripple for API 21 of android, and regular selector on older -->
    <item name="android:foreground">?android:selectableItemBackground</item>
    <!-- Resting Elevation from Material guidelines -->
    <item name="cardElevation">2dp</item>
    <!-- Add corner Radius -->
    <item name="cardCornerRadius">2dp</item>
    <item name="android:clickable">true</item>
    <item name="android:layout_margin">8dp</item>
</style>

이것은 사용하고 있습니다 android.support.v7.widget.CardView

그런 다음 레이아웃 파일에서 스타일을 설정하십시오.

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     style="@style/MyCardViewStyle">
    <!-- Other fields-->
 </android.support.v7.widget.CardView>

gradle을 통해 Android 스튜디오를 사용하여 appcompat-v7 라이브러리를 가져와야합니다.

 dependencies {
     compile 'com.android.support:appcompat-v7:22.2.0'
 }

도움이 되었기를 바랍니다. 행복한 코딩


에서 JAVA

cardView.setCardBackgroundColor(0xFFFEFEFE);

안드로이드는 ARGB 색상을 사용합니다. 하드 코딩 된 색상 (0xFF + RGB COLOR)과 같이 사용할 수 있습니다.


recylerView에서 CardViews를 포맷하는 것과 비슷한 문제가 발생했습니다.

이 간단한 솔루션이 작동하지만 최상의 솔루션인지 확실하지 않지만 저에게 효과적이었습니다.

mv_cardView.getBackground().setTint(Color.BLUE)

It gets the background Drawable of the cardView and tints it.


I came across the same issue while trying to create a cardview programmatically, what is strange is that looking at the doc https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int%29, Google guys made public the api to change the background color of a card view but weirdly i didn't succeed to have access to it in the support library, so here is what worked for me:

CardViewBuilder.java

    mBaseLayout = new FrameLayout(context);
    // FrameLayout Params
    FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    mBaseLayout.setLayoutParams(baseLayoutParams);

    // Create the card view.
    mCardview = new CardView(context);
    mCardview.setCardElevation(4f);
    mCardview.setRadius(8f);
    mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
    CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    cardLayoutParams.setMargins(12, 0, 12, 0);
    mCardview.setLayoutParams(cardLayoutParams);
    // Add the card view to the BaseLayout
    mBaseLayout.addView(mCardview);

    // Create a child view for the cardView that match it's parent size both vertically and horizontally
    // Here i create a horizontal linearlayout, you can instantiate the view of your choice
    mFilterContainer = new LinearLayout(context);
    mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
    mFilterContainer.setPadding(8, 8, 8, 8);
    mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));

    // And here is the magic to get everything working
    // I create a background drawable for this view that have the required background color
    // and match the rounded radius of the cardview to have it fit in.
    mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);

    // Add the horizontal linearlayout to the cardview.
    mCardview.addView(mFilterContainer);

filter_container_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>

Doing that i succeed in keeping the cardview shadow and rounded corners.


I have got the same problem on Xamarin.Android - VS (2017)

The Solution that worked for me:

SOLUTION

In your XML file add:

 xmlns:card_view="http://schemas.android.com/apk/res-auto"

and in your android.support.v7.widget.CardView element add this propriety:

card_view:cardBackgroundColor="#ffb4b4"

(i.e.)

<android.support.v7.widget.CardView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="12dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="1dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardBackgroundColor="#ffb4b4" />

You can also add cardElevation and cardElevation.

If you want to edit the cardview programmatically you just need to use this code: For (C#)

    cvBianca = FindViewById<Android.Support.V7.Widget.CardView>(Resource.Id.cv_bianca);
    cvBianca.Elevation = 14;
    cvBianca.Radius = 14;
    cvBianca.PreventCornerOverlap = true;
    cvBianca.SetCardBackgroundColor(Color.Red);

And now you can change background color programmatically without lost border, corner radius and elevation.


You can use this in java.

cardView.setCardBackgroundColor(Color.parseColor("#cac8a0"));

code color form http://www.color-hex.com/


Cardview is a bit coy. I had list of colors in my structure and Model is like

class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}

load the model with color, last item on constructure taking from R.color

 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgrıundResource

 cv_add_goal_choose_color.setBackgroundResource(color)

I finally got the corners to stay. This is c#, Xamarin.Android

in ViewHolder:

CardView = itemView.FindViewById<CardView>(Resource.Id.cdvTaskList);

In Adapter:

vh.CardView.SetCardBackgroundColor(Color.ParseColor("#4dd0e1"));

You can use below

cardview.setBackgroundColor(Color.parseColor("#EAEDED"));

try it works easy

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardBackgroundColor="#fff"
    card_view:cardCornerRadius="9dp"
    card_view:cardElevation="4dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">

참고URL : https://stackoverflow.com/questions/26561122/change-the-background-color-of-cardview-programmatically

반응형