3

我有一个绘制资源的可选按钮/ ImageView的是这样的:色调VectorDrawable内绘制资源XML

<selector> 
<item android:state_selected="true"> 
    <layer-list> 
     <item> 
      <shape android:shape="oval"> 
       <solid android:color="@color/blue"/> 
      </shape> 
     </item> 
     <item> 
      <bitmap 
       android:src="@drawable/ic_icon" 
       android:tint="@color/white"/> 

     </item> 
    </layer-list> 
</item> 
<item> 
    <layer-list> 
     <item> 
      <shape android:shape="oval"> 
       <solid android:color="@color/background_unselected"/> 
      </shape> 
     </item> 
     <item> 
      <bitmap 
       android:src="@drawable/ic_icon" 
       android:tint="@color/icon_unselected"/> 
     </item> 
    </layer-list> 
</item> 

,因为我已经切换到使用VectorDrawables上述声明无效因为我无法使用<bitmap>标记引用VectorDrawable。 但据我所知,这是我可以给图标着色的唯一方法。

我也不能在代码中应用Colorfilter,因为这样会着色整个drawable而不仅仅是图标。

有什么建议吗?

回答

1

您可以将颜色定义为属性并在SVG中引用它们。然后可以加载由主题设计的drawable。

短例如:

attributes.xml

<declare-styleable name="vectorColors"> 
    <attr name="primaryColor" format="color" /> 
    <attr name="secondaryColor" format="color" /> 
</declare-styleable> 

ic_icon.xml

<path 
    android:fillColor="?attr/primaryColor" 
    android:pathData="...." /> 
<path 
    android:fillColor="?attr/secondaryColor" 
    android:pathData="...." /> 

styles.xml

<style name="svgColors"> 
    <item name="primaryColor">@color/someColor</item> 
    <!-- also can use #RRGGBB way --> 
    <item name="secondaryColor">#ff0000</item> 
</style> 

然后加载你的主题,并绘制:

Resources.Theme theme = getResources().newTheme(); 
theme.applyStyle(R.style.svgColors, false); 
VectorDrawableCompat drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_icon, theme); 
imageView.setImageDrawable(drawable); 

在你特定的选择就应该更换

<item> 
    <bitmap 
     android:src="@drawable/ic_icon" 
     android:tint="@color/white"/> 
</item> 

通过<item android:drawable="@drawable/ic_icon">

Reference and full example

+0

所以颜色引用现在的工作? – milosmns