简体   繁体   中英

RecyclerView cards. How to set gradient background with Card corner radious?

I want to set the custom gradient background to recyclerView cards also maintain cardCornerRadius already set in the xml code.
Grad.net 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 eg ((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 grad.net 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.

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;
    }
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM