Programmatically change color of shape in layer list

后端 未结 4 2108
礼貌的吻别
礼貌的吻别 2020-12-28 14:24

How can I programmatically change the color (#000000) of a shape in a layer list?

Here is my layer list:



        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 14:42

    
         // Give id
            
                 // CHANGE THIS COLOR
            
        
        
            
                
            
        
    
    

    Then in you code just add

    LayerDrawable layerDrawable = (LayerDrawable) getResources()
                .getDrawable(R.drawable.my_drawable);
    GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
                .findDrawableByLayerId(R.id.gradientDrawble);
    gradientDrawable.setColor(color); // change color
    

    Update Oct-2016

    getDrawable() is now deprecated, you should use ContextCompat.getDrawable(context, color) instead.

    Beside, if you get the LayerDrawable by findDrawableByLayerId(), then you had to call view.setBackground(layerDrawable) for this to take effect. Alternatively, instantiating the layerDrawable by view.getBackground() also worked.

提交回复
热议问题