Android动态设置shape形状背景,GradientDrawable动态设置背景色、圆角

1、静态设置

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--填充色-->
    <!--<solid android:color="#FF409DFE"></solid>-->
    <solid android:color="#00000000"></solid>

    <!-- 矩形的边线 -->
    <!--<stroke android:color="#7097E4"
        android:width="1dp"></stroke>-->

    <!--圆角大小-->
    <corners
        android:bottomRightRadius="18dp"
        android:topRightRadius="18dp"
        ></corners>
    <!--android:radius="10dp"-->

    <!--android:topLeftRadius="7dp"
    android:bottomLeftRadius="7dp"-->
</shape>

  

2、代码动态设置:

//设置图片四个角圆形半径:1、2两个参数表示左上角,3、4表示右上角,5、6表示右下角,7、8表示左下角
                        val k = floatArrayOf(
                            DensityUtil.dip2px(context,18F).toFloat(),//左上
                            DensityUtil.dip2px(context,18F).toFloat(),//左上
                            0F,
                            0F,
                            0F,
                            0F,
                            DensityUtil.dip2px(context,18F).toFloat(),//左下角
                            DensityUtil.dip2px(context,18F).toFloat(),//左下角
                        )
                        val drawable = GradientDrawable()
                        //drawable.cornerRadius = DensityUtil.dip2px(context,18F).toFloat()
                        drawable.cornerRadii = k
                        //drawable.setStroke(1, Color.parseColor("#cccccc"))
                        drawable.setColor(Color.parseColor(data.color1))
                        holder.binding.viewColor1.setBackgroundDrawable(drawable)

  

 

 

参考于:

https://www.twblogs.net/a/5d010ee3bd9eee14644f96fc/?lang=zh-cn

https://blog.csdn.net/sinat_41890480/article/details/108773488

posted on 2022-09-28 19:41  巫山老妖  阅读(1058)  评论(0编辑  收藏  举报