以编程方式更新android Vector Drawable

Jas*_*ter 28 android android-vectordrawable

我有一个VectorDrawable由9个矩形组成.这被定义为drawables文件夹中的XML.我将此设置作为我在xml中声明的ImageView的背景.android:src="@drawable/squares00" 我想在运行时以编程方式更改一个或多个方块的颜色.我知道有办法使用VectorDrawable动画来做到这一点.但我想知道是否有更简单的方法来访问我在java中的vectorDrawable,更新其属性(设置一个或多个矩形的填充颜色),然后使用更新的VectoDrawable更新图像背景.我的目标是Android API 21(棒棒糖)

Eya*_*ran 21

简而言之:

  1. 无法直接访问VectorDrawable中的内部元素.
  2. AnimatedVectorDrawable只能访问内部元素.
  3. 使用AnimatedVectorDrawable来模拟您需要的内容.

长:

1.您无权访问

查看VectorDrawable源代码将显示内部元素信息存储在内部私有状态类中.通过名称公开内部元素的唯一方法是,但遗憾的是它是包私有(默认) - 您不能使用它(除非您使用反射).VectorDrawableStategetTargetByName

2. AnimatedVectorDrawable只能访问

getTargetByName仅由AnimatedVectorDrawable使用,我们可以通过搜索方法的用法找到它.

3.使用AnimatedVectorDrawable

所以现在我们看到这是唯一可用的选项,例如,我们可以尝试以下方法将元素"rect2"的颜色从白色更改为黑色:

change_color.xml:

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="0"
        android:propertyName="fillColor"
        android:valueFrom="@color/white"
        android:valueTo="@color/black"/>
</set>
Run Code Online (Sandbox Code Playgroud)

animation.xml:

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:drawable="@drawable/vectordrawable" >
    <target
        android:name="rect2"
        android:animation="@anim/change_color" />
</animated-vector>
Run Code Online (Sandbox Code Playgroud)

并使用此处描述的方法.

注意

如果以上仍然不适合您,您可以尝试以下方法:

  • 复制整个VectorDrawable并调整它(未测试)
  • 使用反射getTargetByName来获取内部元素.您需要首先确保mutate对象.