使用一个vector,首先得创建一个vector_square.xml文件在/drawable文件夹下,如下 :(安卓5.0以上直接使用,以下需要导入兼容包)
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="72dp"
android:height="72dp"
android:viewportHeight="500"
android:viewportWidth="500">
<group
android:name="rotationGroup"
android:pivotX="250.0"
android:pivotY="250.0"
android:rotation="0">
<path
android:name="square"
android:fillColor="#ff0000"
android:pathData="M100,100 L400,100 L400,400 L100,400z" />
</group>
</vector>
这个创建了一个72dp x 72dp大小的svg图片;
此时,这个xml就可以用View来设置Drawable之类的方法来使用。例如ImageView.setImageDrawable(Drawable);
接着是配置文件,类似与Button的selector吧,在/drawable下创建vector_squar_rotation_anim_config.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/square">
<target
android:name="rotationGroup"
android:animation="@animator/vector_squar_rotation_anim" />
</animated-vector>
再接着是创建对应的动画文件,也就是上面代码第5行的vector_squar_rotation_anim,在/animator下创建vector_squar_rotation_anim.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="t"
android:valueFrom="0"
android:valueTo="360" />
接着在xml布局文件下这样写:
<ImageView
android:elevation="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/vector_squar_rotation_anim_config" />
这样就完成了xml的配置;接着在java代码里这样写
AnimatedVectorDrawable anim = (AnimatedVectorDrawable) ((ImageView)v).getDrawable();anim.start();
以上就完成了动画的使用
注意: objectAnimator的propertyName目前只知道支持如下属性:fillColor, rotation, pathData,trimPathEnd,trimPathStart;
前三种使用时需要在vector.xxml里用group包住path节点,后两种反之。