Drawable Resource xml中的T​​int VectorDrawable

cwi*_*ner 9 android tint android-resources android-vectordrawable

我有一个可选择的Button/ImageView的可绘制资源,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

有什么建议?

小智 2

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

简短的例子:

属性.xml

<declare-styleable name="vectorColors">
    <attr name="primaryColor" format="color" />
    <attr name="secondaryColor" format="color" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

ic_icon.xml

<path
    android:fillColor="?attr/primaryColor"
    android:pathData="...." />
<path
    android:fillColor="?attr/secondaryColor"
    android:pathData="...." />
Run Code Online (Sandbox Code Playgroud)

样式.xml

<style name="svgColors">
    <item name="primaryColor">@color/someColor</item> 
    <!-- also can use #RRGGBB way -->
    <item name="secondaryColor">#ff0000</item>
</style>
Run Code Online (Sandbox Code Playgroud)

然后加载你的主题和绘图:

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

在您的特定选择器中,您应该替换

<item>
    <bitmap
        android:src="@drawable/ic_icon"
        android:tint="@color/white"/>
</item>
Run Code Online (Sandbox Code Playgroud)

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

参考和完整示例

  • 这不起作用,&lt;bitmap&gt; 需要位图可绘制,这会因 XmlPullParserException“&lt;bitmap&gt; 需要有效的 'src' 属性”而崩溃 (6认同)