Home > Back-end >  RecyclerView cards. How to set gradient background with Card corner radious?
RecyclerView cards. How to set gradient background with Card corner radious?

Time:04-28

I want to set the custom gradient background to recyclerView cards also maintain cardCornerRadius already set in the xml code.
Gradinet background I set in the adapter with command:
holder.itemView.setBackground(R.drawable.gradient1);
The problem is, when I use code above cardCornerRadius disappear. I know that I have to use something like e.g ((CardView)holder.itemView).setCardBackgroundColor(Color.RED);
but it requires the color as integer in the parameter.
In my code there is gradient(drawable) as background.
So how can I use gradinet as background also with corner radius?
If it is possible I would like to remain the cardCornerRadious parameter in xml code.
I don't want to set it programatically.

CodePudding user response:

Try this Code..

cornerLeft = 80f;
cornerTop = 80f;
cornerRight = 80f;
cornerBottom = 80f;


mMainUserInfo.setBackground(getLayoutBackgroundGrad(cornerLeft, cornerTop, cornerRight, cornerBottom));

    
public GradientDrawable getLayoutBackgroundGrad(float cornerLeft, float cornerTop, float cornerRight, float cornerBottom) {
    try {
        GradientDrawable gradient = new GradientDrawable(
                Orientation.BOTTOM_TOP, new int[]{
                Color.parseColor("#ffe259"),
                Color.parseColor("#ffa751")});
        gradient.setShape(GradientDrawable.RECTANGLE);
        gradient.setCornerRadii(new float[]{cornerLeft, cornerLeft, cornerTop, cornerTop,
                cornerRight, cornerRight, cornerBottom, cornerBottom});
        // int color = Color.parseColor(strockColor);
        // gradient.setStroke(1, color);
        return gradient;
    } catch (Exception e) {
        return null;
    }
}

CodePudding user response:

If you don't want to set it programatically you can try this workaround.

<androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardElevation="2dp"
        app:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/round_corner">

        </LinearLayout>

    </androidx.cardview.widget.CardView>

round_corner.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    
    <gradient
        android:angle="270"
        android:endColor="#B9ED5050"
        android:startColor="#B9534A4A" />

</shape>
  • Related