Change fillColor of a vector in android programmatically

后端 未结 5 2290
情书的邮戳
情书的邮戳 2020-12-15 03:13

I want to edit the fill Color of a vector-file in Android programmatically.

In the xml-file I can set my color with the attribute android:fillColor

5条回答
  •  难免孤独
    2020-12-15 03:27

    This is exactly what you need. Credits to @emmaguy, the author of the post. I just added the full support of Support Library 23.4+, which enables you to stop generating pngs at runtime:

     // Gradle Plugin 2.0+  
     android {  
       defaultConfig {  
         vectorDrawables.useSupportLibrary = true  
       }  
     } 
    

    And if this line is set on your Activity's or Application's onCreate:

    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    

    You can use your SVGs not only with srcCompat but also with other attributes such as drawableLeft, background, etc. in TextView, ToggleButton and so on. It also works if used on selectors.

    Note: I modified the code to use VectorDrawableCompat.create instead of ResourcesCompat.getDrawable. Otherwise it would not work and throw org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: invalid drawable tag vector.


    Medium post content:

    First, we create attributes for the two kinds of bauble, so we can change their colours:

    
        
        
    
    

    Then, in the VectorDrawable, set the parts we want to dynamically change to use these attributes:

    
    
    ...
    

    Create themes and set the colours you want to use:

    
    
    
    

    Use the drawable in an ImageView:

    final ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DefaultScene);
    final Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.christmas, wrapper.getTheme());
    imageView.setImageDrawable(drawable);
    

    That’s it! When you want to change the colours, simply set a different theme and your drawable will update. See the GitHub repo for a full sample.

提交回复
热议问题