在使用shape的同时,用代码修改shape的颜色属性

来源:互联网 发布:夜跑装备 知乎 编辑:程序博客网 时间:2024/06/06 11:30

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

可以修改View的背景颜色,形状等属性


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

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

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.     <corners  
  4.         android:topLeftRadius="8dp"  
  5.         android:topRightRadius="8dp"  
  6.         android:bottomLeftRadius="8dp"  
  7.         android:bottomRightRadius="8dp"/>  
  8.       
  9.     <solid  
  10.         android:color="#00000000"/>  
  11.   
  12. </shape>  

[java] view plain copy
  1. View.setBackgroundColor(color);  
  2. View.setBackgroundDrawable(R.drawable.shape);  

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


最后上网Google了下,找到解决方案了

[java] view plain copy
  1. GradientDrawable myGrad = (GradientDrawable)view.getBackground();  
  2. myGrad.setColor(color);