ym—— Android 5.0学习之AnimatedVec

转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持!

**

前言

示例代码地址:animated-vector-drawable

几句代码,几个配置文件即可实现以上效果,流畅的体验,无缝的动画,赞~!

官方文档:点击传送

AnimatedVectorDrawable类可以去创建一个矢量资源的动画。

你通常在三个XML文件中定义矢量资源的动画载体:

元素的矢量资源,在res/drawable/(文件夹) 元素的矢量资源动画,在res/drawable/(文件夹) < objectAnimator>元素的一个或多个对象动画器,在res/anim/(文件夹) 矢量资源动画能创建和元素属性的动画。元素定义了一组路径或子组,并且元素定义了要被绘制的路径。 当你想要创建动画时去定义矢量资源,使用android:name属性分配一个唯一的名字给组和路径,这样你可以从你的动画定义中查询到它们。 接下来我就以旋转的小三角为例: 看之前我们要思考一个问题,它是如何做到在边旋转的过程中变化形状的。 首先我们先看一下小三角的vector文件: ![](https://box.kancloud.cn/2016-02-23_56cc073e817fd.jpg) 然后在看一下animated-vector文件: ~~~

<target
android:name="v"
android:animation="@anim/path_morph" />
</animated-vector>

从上面代码我们可以看出配置了两个动画,一个是旋转动画一个是变化形状的动画。  
旋转动画:

<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="6000"
android:propertyName="rotation"
android:valueFrom="0"
android:valueTo="360"/>

变化形状动画:

<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="3000"
android:propertyName="pathData"
android:valueFrom="M300,70 l 0,-70 70,70 0,0 -70,70z"
android:valueTo="M300,70 l 0,-70 70,0 0,140 -70,0 z"
android:valueType="pathType"/>

最后我们再来看下它是如何配置到layout里面的:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".ExampleActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:text="@string/example_from_documentation"
android:drawableBottom="@drawable/avd"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:text="@string/rotation_only"
android:drawableBottom="@drawable/avd_rotation_only"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:text="@string/path_morph_only"
android:drawableBottom="@drawable/avd_path_morph_only"/>

3个TextView,我们只需要关注第一个TextView即可,因为其他都是一样的配置。  
配置了一个avb也就是上面贴的animated-vector文件。

最后看一下Activity的启动动画代码:

TextView textView = (TextView) view;
for (final Drawable drawable : textView.getCompoundDrawables()) {
  if (drawable instanceof Animatable) {
    ((Animatable) drawable).start();
  }
}
找到这个view 拿到他们Drawables对象start即可,容易吧,赶紧去试试吧~!
文章导航