zl程序教程

您现在的位置是:首页 >  其他

当前栏目

在使用shape的同一时候,用代码改动shape的颜色属性

属性代码 颜色 时候 同一 Shape 改动 使用
2023-09-11 14:20:59 时间

Android里面常常会使用shape来定制一些View的背景

能够改动View的背景颜色。形状等属性


普通情况下。shape都是在xml文件中面写死了。今天遇到一个需求,View的形状是圆角的,可是颜色是在代码里面设置的

最開始的思路是先在代码里给View设置颜色。再在shape里面设置solid属性为透明色

<?xml version="1.0" encoding="utf-8"?

> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:topLeftRadius="8dp" android:topRightRadius="8dp" android:bottomLeftRadius="8dp" android:bottomRightRadius="8dp"/> <solid android:color="#00000000"/> </shape>


View.setBackgroundColor(color);
View.setBackgroundDrawable(R.drawable.shape);

非常遗憾,不能实现我想要的需求,每设置一次Background,Background就会就会被替换掉


最后上网Google了下,找到解决方式了http://stackoverflow.com/questions/16775891/how-to-change-solid-color-from-the-code

GradientDrawable myGrad = (GradientDrawable)view.getBackground();
myGrad.setColor(color);