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

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


原文地址:https://www.cnblogs.com/gcczhongduan/p/5193846.html