Material Design系列第六篇——Defining Custom Animations
Defining Custom Animations //自定义动画
This lesson teaches you to //本节课知识点
- Customize Touch Feedback //1.自定义触摸反馈
- Use the Reveal Effect //2.使用显示特效
- Customize Activity Transitions //3.自定义activity切换动画
- Animate View State Changes //4.动画视图状态改变
- Animate Vector Drawables //5.动画向量图像
You should also read
Animations in material design give users feedback on their actions and provide visual continuity as users interact with your app. The material theme provides some default animations for buttons and activity transitions, and Android 5.0 (API level 21) and above lets you customize these animations and create new ones:
//在材料设计中的动画将会给用户在操作上带来反馈并且提供可视化持续性的交互体验。材料主题为按钮和activity切换提供了一些默认的动画,在5.0以上可以自己定义和创建这些动画:
- Touch feedback //触摸反馈
- Circular Reveal //圆形显示
- Activity transitions //activity切换
- Curved motion //曲线运动
- View state changes //视图状态改变
Customize Touch Feedback //定制触摸反馈
Touch feedback in material design provides an instantaneous visual confirmation at the point of contact when users interact with UI elements. The default touch feedback animations for buttons use the new RippleDrawable
class, which transitions between different states with a ripple effect.
//在材料设计总触摸反馈在用户与UI的交互时提供实时视觉确认。默认的按钮触摸反馈动画使用RippleDrawable类,在两个不同状态之间的涟漪效果。
In most cases, you should apply this functionality in your view XML by specifying the view background as:
//在大多数情况下,你应该在你的布局中的视图元素应用这个功能通过以下几个元素:
?android:attr/selectableItemBackground
for a bounded ripple //用一个小波纹?android:attr/selectableItemBackgroundBorderless
for a ripple that extends beyond the view //超出边界的波纹
Note: selectableItemBackgroundBorderless
is a new attribute introduced in API level 21. //API21的新属性
Alternatively, you can define a RippleDrawable
as an XML resource using the ripple
element. //或者,你可以通过xml使用ripple元素顶一个RippleDrawable
You can assign a color to RippleDrawable
objects. To change the default touch feedback color, use the theme's android:colorControlHighlight
attribute.
//你可以指定一种颜色在RippleDrawable对象。可以使用android:colorControlHighlight属性更改默认的触摸反馈颜色。
For more information, see the API reference for the RippleDrawable
class. //更多信息,可以查看 RippleDrawable类的API
Use the Reveal Effect //使用显示效果
Reveal animations provide users visual continuity when you show or hide a group of UI elements. The ViewAnimationUtils.createCircularReveal()
method enables you to animate a clipping circle to reveal or hide a view.
//显示动画为显示或隐藏一组UI元素提供了可视化持续性(蔓延效果?)。ViewAnimationUtils.createCircularReveal()方法可以开启一个裁剪的原型的显示效果或者隐藏。
To reveal a previously invisible view using this effect:
//显示一个不可见的视图用这个效果:
// previously invisible view View myView = findViewById(R.id.my_view); // get the center for the clipping circle int cx =(myView.getLeft()+ myView.getRight())/2; int cy =(myView.getTop()+ myView.getBottom())/2; // get the final radius for the clipping circle int finalRadius =Math.max(myView.getWidth(), myView.getHeight()); // create the animator for this view (the start radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy,0, finalRadius); // make the view visible and start the animation myView.setVisibility(View.VISIBLE); anim.start();
To hide a previously visible view using this effect:
//隐藏一个可见的视图用这个效果:
// previously visible view finalView myView = findViewById(R.id.my_view); // get the center for the clipping circle int cx =(myView.getLeft()+ myView.getRight())/2; int cy =(myView.getTop()+ myView.getBottom())/2; // get the initial radius for the clipping circle int initialRadius = myView.getWidth(); // create the animation (the final radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius,0); // make the view invisible when the animation is done anim.addListener(newAnimatorListenerAdapter(){ @Override publicvoid onAnimationEnd(Animator animation){ super.onAnimationEnd(animation); myView.setVisibility(View.INVISIBLE); } }); // start the animation anim.start();
Customize Activity Transitions //自定义Activity切换动画
Figure 1 - A transition with shared elements.
To replay the movie, click on the device screenActivity transitions in material design apps provide visual connections between different states through motion and transformations between common elements. You can specify custom animations for enter and exit transitions and for transitions of shared elements between activities.
//材料设计的activity切换提供在app中的两种不同状态之间通过运动来表现一个视觉连贯并且在两个共同的元素之间转换。你可以在activity的切换中维持共享元素的进入和退出指定一个自定义动画。
- An enter transition determines how views in an activity enter the scene. For example, in the explode enter transition, the views enter the scene from the outside and fly in towards the center of the screen. //一个进入动画意味着activity中的视图如何进入这个场景。例如,在一个散开的变换中,视图进入出纳关键会由外到内飞入屏幕的中间。
- An exit transition determines how views in an activity exit the scene. For example, in the explode exit transition, the views exit the scene away from the center. //一个退出动画决定Activity中的视图如何退出当前场景。例如,在一个散开的退出动画中,视图总是从中间退出。
- A shared elements transition determines how views that are shared between two activities transition between these activities. For example, if two activities have the same image in different positions and sizes, the changeImageTransform shared element transition translates and scales the image smoothly between these activities. //一个共享的元素决定在activity的切换当中是以一个共享的元素作为纽带来变化。例如,如果两个activity拥有同样一张图在不同的位子不同的大小,这个changeImageTransform共享元素在activity的切换时会很平滑的移动和缩放变化。
Android 5.0 (API level 21) supports these enter and exit transitions:
//Android5.0 (API level 21) 支持以下几种变换方式:
- explode - Moves views in or out from the center of the scene. //爆裂式-从一个场景的中间展开或缩起
- slide - Moves views in or out from one of the edges of the scene. //滑动式-从一个出纳关键的边缘过度
- fade - Adds or removes a view from the scene by changing its opacity. //渐变式-通过改变透明度来添加或移除视图
Any transition that extends the Visibility
class is supported as an enter or exit transition. For more information, see the API reference for the Transition
class.
//任何继承Visibility
类的transition都支持进入和退出动画。更多信息,请参考Transition类的API.
Android 5.0 (API level 21) also supports these shared elements transitions:
//Android 5.0 (API level 21) 也支持共享元素的集中变化方式
- changeBounds - Animates the changes in layout bounds of target views. //改变边界-改变目标视图的布局边界的动画
- changeClipBounds - Animates the changes in clip bounds of target views. //改变裁剪边界-改变目标视图的裁剪边界的动画
- changeTransform - Animates the changes in scale and rotation of target views. //变形-改变目标视图的缩放和旋转角度
- changeImageTransform - Animates changes in size and scale of target images. //改变图像变形-改变目标视图的大小和缩放
When you enable activity transitions in your app, the default cross-fading transition is activated between the entering and exiting activities.
//当你在app中开启了activity的切换,在进入和退出的activity将会激活默认的融合渐变。
![](http://images0.cnblogs.com/blog/307289/201501/251659585817928.png)
Figure 2 - A scene transition with one shared element. 共享元素的变化场景
Specify custom transitions //指定自定义切换动画
First, enable window content transitions with the android:windowContentTransitions
attribute when you define a style that inherits from the material theme. You can also specify enter, exit, and shared element transitions in your style definition:
//首先,在你定义材料主题中内置的style时通过android:windowContentTransitions
属性开启窗口内容的变化。你可以在你的style定义中指定进入、退出和共享元素的变化动画。
<style name="BaseAppTheme"parent="android:Theme.Material"> <!-- enable window content transitions --> <item name="android:windowContentTransitions">true</item> <!-- specify enter and exit transitions --> <item name="android:windowEnterTransition">@transition/explode</item> <item name="android:windowExitTransition">@transition/explode</item> <!-- specify shared element transitions --> <item name="android:windowSharedElementEnterTransition"> @transition/change_image_transform</item> <item name="android:windowSharedElementExitTransition"> @transition/change_image_transform</item> </style>
The change_image_transform
transition in this example is defined as follows:
//例子里change_image_transform动画定义在以下
<!-- res/transition/change_image_transform.xml --> <!-- (see also Shared Transitions below) --> <transitionSetxmlns:android="http://schemas.android.com/apk/res/android"> <changeImageTransform/> </transitionSet>
The changeImageTransform
element corresponds to the ChangeImageTransform
class. For more information, see the API reference for Transition
.
//这个changeImageTransform
元素相当于ChangeImageTransform
类。更多相关信息,请参考TransitionAPI。
To enable window content transitions in your code instead, call the Window.requestFeature()
method:
//用代码来实现窗口内容的变化,可以调用Window.requestFeature()方法来代替:
// inside your activity (if you did not enable transitions in your theme) getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); // set an exit transition getWindow().setExitTransition(newExplode());
To specify transitions in your code, call these methods with a Transition
object:
//在你的代码中指定变化方式,可以调用下面的方法给定一个Transition
对象:
Window.setEnterTransition()
Window.setExitTransition()
Window.setSharedElementEnterTransition()
Window.setSharedElementExitTransition()
The setExitTransition()
and setSharedElementExitTransition()
methods define the exit transition for the calling activity. The setEnterTransition()
and setSharedElementEnterTransition()
methods define the enter transition for the called activity.
//这两个退出动画方法必须在正在调入的activity调用。两个进入的方法要定义在被调入的activity。
To get the full effect of a transition, you must enable window content transitions on both the calling and called activities. Otherwise, the calling activity will start the exit transition, but then you'll see a window transition (like scale or fade).
//要获得完整的切换效果,你必须在主调和被调的activity中开启窗口内容变化。否则,主调的actiivty会实行退出动画,但是然后会看到窗口的变化(就像缩放或渐变)。
To start an enter transition as soon as possible, use the Window.setAllowEnterTransitionOverlap()
method on the called activity. This lets you have more dramatic enter transitions.
Start an activity using transitions //用transitions 来启动一个activity
If you enable transitions and set an exit transition for an activity, the transition is activated when you launch another activity as follows:
//如果开启了transitions并且为activity设置了退出动画,当你启动另一个activity的时候这个动画将会被激活。
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
If you have set an enter transition for the second activity, the transition is also activated when the activity starts. To disable transitions when you start another activity, provide a null
options bundle.
//如果你设置第二个activity的进入动画,同样地,当它启动的时候动画也一样会被激活。如果想在启动其他activity的时候禁止动画,只需要提供一个Null的Bundle参数。
Start an activity with a shared element //通过一个共享元素来启动activity
To make a screen transition animation between two activities that have a shared element:
//在两个activity之间通过一个共享元素来作切换动画:
- Enable window content transitions in your theme. //1.在你的主题中开启窗口内容变换
- Specify a shared elements transition in your style. //2.在你的style当中指定一个共享元素
- Define your transition as an XML resource. //3.定义一个xml的动画xml资源
- Assign a common name to the shared elements in both layouts with the
android:transitionName
attribute. //4.在两个activity的布局指定一个共同名字的共享元素 - Use the
ActivityOptions.makeSceneTransitionAnimation()
method. //5.使用ActivityOptions.makeSceneTransitionAnimation()
方法
// get the element that receives the click event final View imgContainerView = findViewById(R.id.img_container); // get the common element for the transition in this activity final View androidRobotView = findViewById(R.id.image_small); // define a click listener imgContainerView.setOnClickListener(newView.OnClickListener(){ @Override publicvoid onClick(View view){ Intent intent =newIntent(this,Activity2.class); // create the transition animation - the images in the layouts // of both activities are defined with android:transitionName="robot" ActivityOptions options =ActivityOptions .makeSceneTransitionAnimation(this, androidRobotView,"robot"); // start the new activity startActivity(intent, options.toBundle()); } });
For shared dynamic views that you generate in your code, use the View.setTransitionName()
method to specify a common element name in both activities.
To reverse the scene transition animation when you finish the second activity, call the Activity.finishAfterTransition()
method instead of Activity.finish()
.
//如果你想用你代码实现共享视图,在两个activity通过 View.setTransitionName()方法指定一个共享元素。当结束第二个activity的时候反转切换动画,用
Activity.finishAfterTransition()
来替代Activity.finish()。
Start an activity with multiple shared elements //通过多个共享元素来启动activity
To make a scene transition animation between two activities that have more than one shared element, define the shared elements in both layouts with the android:transitionName
attribute (or use the View.setTransitionName()
method in both activities), and create an ActivityOptions
object as follows:
//如果需要在两个acitivity切换动画中绑定多个共享元素,把共享元素在两个activity的布局中用android:transitionName属性定义(或者在两个activity中使用 View.setTransitionName()方法
),创建ActivityOptions对象如
下:
ActivityOptions options =ActivityOptions.makeSceneTransitionAnimation(this, Pair.create(view1,"agreedName1"), Pair.create(view2,"agreedName2"));
Use Curved Motion //使用曲线运动
Animations in material design rely on curves for time interpolation and spatial movement patterns. With Android 5.0 (API level 21) and above, you can define custom timing curves and curved motion patterns for animations.
//材质设计的动画依靠曲线时间插值和可移动的空间模块。在5.0以上动画可以定义时间曲线和曲线运动部分。
The PathInterpolator
class is a new interpolator based on a Bézier curve or a Path
object. This interpolator specifies a motion curve in a 1x1 squa
re, with anchor points at (0,0) and (1,1) and control points as specified using the constructor arguments. You can also define a path interpolator as an XML resource:
//PathInterpolator类是一个新的基于 Bézier curve或一个Path
对象的插值器。这个插值器指定一个在1x1的正方形内运动曲线,用一个描点在(0,0)和(1,1)和指定的控制点(不太明白)。你也可以用xml资源定义一个路径插值器
<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:controlX1="0.4" android:controlY1="0" android:controlX2="1" android:controlY2="1"/>
The system provides XML resources for the three basic curves in the material design specification:
//在材质设计中系统提供三种基础曲线的XML资源
@interpolator/fast_out_linear_in.xml
@interpolator/fast_out_slow_in.xml
@interpolator/linear_out_slow_in.xml
You can pass a PathInterpolator
object to the Animator.setInterpolator()
method.
//你可以通过一个PathInterpolator对象使用Animator.setInterpolator()
方法
The ObjectAnimator
class has new constructors that enable you to animate coordinates along a path using two or more properties at once. For example, the following animator uses a Path
object to animate the X and Y properties of a view:
//这个ObjectAnimator
类拥有一个新的构造,开启你的动画沿着用两个或更多属性的的路径到坐标点。例如,下面的动画用一个Path对象移动到一个视图的X和Y:
ObjectAnimator mAnimator; mAnimator =ObjectAnimator.ofFloat(view,View.X,View.Y, path); ... mAnimator.start();
Animate View State Changes //动画视图状态的改变
The StateListAnimator
class lets you define animators that run when the state of a view changes. The following example shows how to define an StateListAnimator
as an XML resource:
//StateListAnimator
类让你定义一个视图的状态改变动画。下面的例子展示了怎么用XML资源定义个StateListAnimator动画
<!-- animate the translationZ property of a view when pressed --> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <set> <objectAnimator android:propertyName="translationZ" android:duration="@android:integer/config_shortAnimTime" android:valueTo="2dp" android:valueType="floatType"/> <!-- you could have other objectAnimator elements here for "x" and "y", or other properties --> </set> </item> <item android:state_enabled="true" android:state_pressed="false" android:state_focused="true"> <set> <objectAnimator android:propertyName="translationZ" android:duration="100" android:valueTo="0" android:valueType="floatType"/> </set> </item> </selector>
To attach custom view state animations to a view, define an animator using the selector
element in an XML resource file as in this example, and assign it to your view with the android:stateListAnimator
attribute. To assign a state list animator to a view in your code, use the AnimationInflater.loadStateListAnimator()
method, and assign the animator to your view with the View.setStateListAnimator()
method.
// 给视图附上自定义视图状态动画,就像这个例子用XML资源文件的selector元素定义一个动画,并且把它指定到视图的android:stateListAnimator
属性。如果要用代码指定视图的状态列表动画,用AnimationInflater.loadStateListAnimator()方法,并且通过View.setStateListAnimator()方法到你的额视图中。
When your theme extends the material theme, buttons have a Z animation by default. To avoid this behavior in your buttons, set the android:stateListAnimator
attribute to @null
.
// 当你的主题继承至material 主题时,按钮有一个Z的默认动画。如果要禁止它需要把 android:stateListAnimator
属性置为@null。
The AnimatedStateListDrawable
class lets you create drawables that show animations between state changes of the associated view. Some of the system widgets in Android 5.0 use these animations by default. The following example shows how to define an AnimatedStateListDrawable
as an XML resource:
//AnimatedStateListDrawable
类让你创建一个在视图上状态变化之间的动画drawables 。在5.0有些控件默认用了这个动画。下面的例子展示如何用XML资源定义一个AnimatedStateListDrawable
:
<!-- res/drawable/myanimstatedrawable.xml --> <animated-selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- provide a different drawable for each state--> <item android:id="@+id/pressed"android:drawable="@drawable/drawableP" android:state_pressed="true"/> <item android:id="@+id/focused"android:drawable="@drawable/drawableF" android:state_focused="true"/> <item android:id="@id/default" android:drawable="@drawable/drawableD"/> <!-- specify a transition --> <transition android:fromId="@+id/default"android:toId="@+id/pressed"> <animation-list> <item android:duration="15"android:drawable="@drawable/dt1"/> <item android:duration="15"android:drawable="@drawable/dt2"/> ... </animation-list> </transition> ... </animated-selector>
Animate Vector Drawables //矢量动画
Vector Drawables are scalable without losing definition. The AnimatedVectorDrawable
class lets you animate the properties of a vector drawable.
//矢量图像是不会随着放大缩小而丢失品质的。AnimatedVectorDrawable
类让你的动画可以使用矢量图像。
You normally define animated vector drawables in three XML files:
//你通常在以下三个文件中定义矢量动画
- A vector drawable with the
<vector>
element inres/drawable/ //在res/drawable/定义一个
<vector>元素图像
- An animated vector drawable with the
<animated-vector>
element inres/drawable/ //在res/drawable/使用<animated-vector>元素
- One or more object animators with the
<objectAnimator>
element inres/anim/ //在res/anim/通过
<objectAnimator>元素定义
多个对象动画
Animated vector drawables can animate the attributes of the <group>
and <path>
elements. The <group>
elements defines a set of paths or subgroups, and the <path>
element defines paths to be drawn.
//矢量动画可以定义 <group>
和 <path>
元素。<group>元素定义一个路径集合或子集,<path>元素定义绘制路径。
When you define a vector drawable that you want to animate, use the android:name
attribute to assign a unique name to groups and paths, so you can refer to them from your animator definitions. For example:
//当你定义一个矢量图形,使用 android:name
属性在组和路径当中指定一个唯一的名字,所以你可以在你的动画定义时引用他们。例如:
<!-- res/drawable/vectordrawable.xml --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="64dp" android:width="64dp" android:viewportHeight="600" android:viewportWidth="600"> <group android:name="rotationGroup" android:pivotX="300.0" android:pivotY="300.0" android:rotation="45.0"> <path android:name="v" android:fillColor="#000000" android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z"/> </group> </vector>
The animated vector drawable definition refers to the groups and paths in the vector drawable by their names:
//在定义矢量动画的时候引用 groups 和paths
<!-- res/drawable/animvectordrawable.xml --> <animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/vectordrawable"> <target android:name="rotationGroup" android:animation="@anim/rotation"/> <target android:name="v" android:animation="@anim/path_morph"/> </animated-vector>
The animation definitions represent ObjectAnimator
or AnimatorSet
objects. The first animator in this example rotates the target group 360 degrees:
//下面的动画定义代表ObjectAnimator
或者AnimatorSet
对象。下面的例子中第一个动画就是将目标组旋转360度。
<!-- res/anim/rotation.xml --> <objectAnimator android:duration="6000" android:propertyName="rotation" android:valueFrom="0" android:valueTo="360"/>
The second animator in this example morphs the vector drawable's path from one shape to another. Both paths must be compatible for morphing: they must have the same number of commands and the same number of parameters for each command.
//这个例子中的第二个动画变种是从一个图形到另一个的矢量路径。两种路径必须兼容:他们必须有同样的命令数字和每一个命令的参数同样的名字。
<!-- res/anim/path_morph.xml --> <setxmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator 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"/> </set>
For more information, see the API reference for AnimatedVectorDrawable
.
//更多信息,可以参考AnimatedVectorDrawableAPI。