Android dynamically change shape fill color

At work, different backgrounds need to be displayed according to different bank cards. Since there are many banks, it is impossible to use pictures. I thought of using Shape, but there are many, and it is impossible to write it in the XML file of shape.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#971417" ></solid>

    <corners  android:topLeftRadius="10dp"    android:topRightRadius="10dp"
        android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp"/>
   <!-- <stroke android:width="1dp" android:color="#971417" />-->
</shape>

 Finally decided to use code

public static Drawable getBgDrawableByBankNo(Context ctx, String bankNo){
       // int strokeWidth = 5; // 0dp border width
        //int roundRadius=TypedValue.applyDimension(); // 10dp corner radius
       // int strokeColor = Color.parseColor("#2E3135");//border color
        int fillColor = Color.parseColor(" #971417 ");//Inner fill color
        int topLeftRadius= DisplayUtil.dip2px(ctx,10);
        int topRightRadius=topLeftRadius;
        int bottomRightRadius=0;
        int bottomLeftRadius=0;

        GradientDrawable gd = new GradientDrawable();//创建drawable
        gd.setGradientType(GradientDrawable.RECTANGLE);
         gd.setColor(fillColor);
       // gd.setCornerRadius(roundRadius);
        //The two parameters 1 and 2 represent the upper left corner, 3 and 4 represent the upper right corner, 5 and 6 represent the lower right corner, and 7 and 8 represent the lower left corner.
        gd.setCornerRadii(new float[] { topLeftRadius,
                topLeftRadius, topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius, bottomLeftRadius,
                bottomLeftRadius });
       // gd.setStroke(strokeWidth, strokeColor);

        return gd;
    }

 use

iv.setBackgroundDrawable(xxx);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326309480&siteId=291194637