Android动态改变shape填充颜色

本文介绍了一种使用代码动态生成不同银行卡背景的方法,避免了大量图片资源的使用,并通过GradientDrawable实现了不同圆角和颜色的背景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中需要依据不同的银行卡显示不同背景,由于银行很多,不可能用图片,想到了用Shape,但数量多,也不可能写死在shape的XML文件中,

<?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>

 最后决定用代码方式

 public static Drawable getBgDrawableByBankNo(Context ctx, String bankNo){
       // int strokeWidth = 5; // 0dp 边框宽度
        //int roundRadius=TypedValue.applyDimension(); // 10dp 圆角半径
       // int strokeColor = Color.parseColor("#2E3135");//边框颜色
        int fillColor = Color.parseColor("#971417");//内部填充颜色
        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);
        //1、2两个参数表示左上角,3、4表示右上角,5、6表示右下角,7、8表示左下角
        gd.setCornerRadii(new float[] { topLeftRadius,
                topLeftRadius, topRightRadius, topRightRadius,
                bottomRightRadius, bottomRightRadius, bottomLeftRadius,
                bottomLeftRadius });
       // gd.setStroke(strokeWidth, strokeColor);

        return gd;
    }

 使用

iv.setBackgroundDrawable(xxx);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值