Property Animation筆記

本筆記的原文本鏈接

Property Animation Overview 屬性動(dòng)畫總覽

The property animation system is a robust framework that allows you to animate almost anything.
屬性動(dòng)畫系統(tǒng)是一個(gè)健壯的框架赤套,它允許你為任何東西創(chuàng)建動(dòng)畫。
You can define an animation to change any object property over time, regardless of whether it draws to the screen or not.
你可以定義一個(gè)隨時(shí)間改變?nèi)魏螌?duì)象屬性的動(dòng)畫获雕,無論他是否繪制在屏幕上占哟。
A property animation changes a property's (a field in an object) value over a specified length of time.
屬性動(dòng)畫會(huì)在指定的時(shí)間長(zhǎng)度內(nèi)更改屬性的(對(duì)象中的字段)值眷唉。
To animate something, you specify the object property that you want to animate, such as an object's position on the screen, how long you want to animate it for, and what values you want to animate between.
為某個(gè)東西創(chuàng)建動(dòng)畫,你需要指定你想要?jiǎng)?chuàng)建動(dòng)畫的這個(gè)對(duì)象的屬性姑荷,例如一個(gè)對(duì)象在屏幕上的位置,你想要為它動(dòng)畫多久校翔,和你想要在什么值之間動(dòng)畫。
The property animation system lets you define the following characteristics of an animation:
屬性動(dòng)畫系統(tǒng)允許你定義動(dòng)畫以下的這些的特性:

  • Duration: You can specify the duration of an animation. The default length is 300 ms.
  • 持續(xù)時(shí)間:你可以指定動(dòng)畫的持續(xù)時(shí)間灾前。默認(rèn)的長(zhǎng)度是300ms
  • Time interpolation: You can specify how the values for the property are calculated as a function of the animation's current elapsed time.
  • 時(shí)間插值:您可以指定屬性的值如何作為動(dòng)畫當(dāng)前流逝時(shí)間的函數(shù)進(jìn)行計(jì)算的防症。
  • Repeat count and behavior: You can specify whether or not to have an animation repeat when it reaches the end of a duration and how many times to repeat the animation. You can also specify whether you want the animation to play back in reverse. Setting it to reverse plays the animation forwards then backwards repeatedly, until the number of repeats is reached.
  • 重復(fù)計(jì)數(shù)和行為:當(dāng)動(dòng)畫到達(dá)持續(xù)時(shí)間的終端時(shí),你可以定義動(dòng)畫是否重復(fù)和重復(fù)次數(shù)。你還可以指定是否想要?jiǎng)赢嫹聪虿シ鸥嫦!TO(shè)置為反向播放動(dòng)畫向前,然后向后重復(fù)烧给,直到達(dá)到重復(fù)的數(shù)量燕偶。設(shè)置它反向向前播放這個(gè)動(dòng)畫,然后向后重復(fù)础嫡,直到重復(fù)次數(shù)到達(dá)為止指么。
  • Animator sets: You can group animations into logical sets that play together or sequentially or after specified delays.
  • 動(dòng)畫集:你可以將動(dòng)畫分組為邏輯集合,它們?cè)谝黄鸹虬错樞蚧蛟谥付ǖ难舆t之后播放榴鼎。
  • Frame refresh delay: You can specify how often to refresh frames of your animation. The default is set to refresh every 10 ms, but the speed in which your application can refresh frames is ultimately dependent on how busy the system is overall and how fast the system can service the underlying timer.
  • 幀刷新延遲:你可以指定刷新動(dòng)畫幀的頻率伯诬。默認(rèn)設(shè)置為每10毫秒刷新一次,但應(yīng)用程序可以刷新幀的速度最終取決于整個(gè)系統(tǒng)的繁忙程度以及系統(tǒng)能為底層定時(shí)器服務(wù)的速度巫财。

How Property Animation Works 屬性動(dòng)畫是如何工作的

First, let's go over how an animation works with a simple example.
首先盗似,讓我們通過一個(gè)簡(jiǎn)單的示例走一遍動(dòng)畫是如何工作的。
Figure 1 depicts a hypothetical object that is animated with its x property, which represents its horizontal location on a screen. The duration of the animation is set to 40 ms and the distance to travel is 40 pixels.
圖1描述了一個(gè)假想對(duì)象平项,其對(duì)象是x屬性赫舒,表示它在屏幕上的水平位置。動(dòng)畫的持續(xù)時(shí)間設(shè)置為40毫秒闽瓢,移動(dòng)距離為40像素接癌。
Every 10 ms, which is the default frame refresh rate, the object moves horizontally by 10 pixels.
每10ms,這是默認(rèn)的幀刷新率扣讼,這個(gè)對(duì)象水平移動(dòng)10像素缺猛。這個(gè)40ms的終點(diǎn)。
At the end of 40ms, the animation stops, and the object ends at horizontal position 40.
在40ms椭符,動(dòng)畫停止荔燎,同時(shí)這個(gè)對(duì)象停止在水平位置40的地方。
This is an example of an animation with linear interpolation, meaning the object moves at a constant speed.
這是一個(gè)具有水平線性插值的動(dòng)畫示例艰山,意味著這個(gè)對(duì)象以恒定的速度移動(dòng)湖雹。


Figure 1. Example of a linear animation

You can also specify animations to have a non-linear interpolation.
你也可以指定具有非線性插值的動(dòng)畫。
Figure 2 illustrates a hypothetical object that accelerates at the beginning of the animation, and decelerates at the end of the animation.
圖2說明了一個(gè)假設(shè)的對(duì)象曙搬,在動(dòng)畫開始時(shí)加速摔吏,然后在動(dòng)畫結(jié)束時(shí)減速。
The object still moves 40 pixels in 40 ms, but non-linearly. In the beginning, this animation accelerates up to the halfway point then decelerates from the halfway point until the end of the animation.
這個(gè)對(duì)象仍然在40ms移動(dòng)40像素纵装,但是是非線性的征讲。一開始,這個(gè)動(dòng)畫加速直到中間點(diǎn)橡娄。然后诗箍,從中間點(diǎn)減速直到動(dòng)畫結(jié)束。
As Figure 2 shows, the distance traveled at the beginning and end of the animation is less than in the middle.
如圖2所示挽唉,動(dòng)畫開始和結(jié)束的一段時(shí)間內(nèi)所走的距離小于中間一段時(shí)間的距離滤祖。


Figure 2. Example of a non-linear animation

Let's take a detailed look at how the important components of the property animation system would calculate animations like the ones illustrated above.
讓我們?cè)敿?xì)看看屬性動(dòng)畫系統(tǒng)的重要組件如何計(jì)算上面提到的動(dòng)畫筷狼。
Figure 3 depicts how the main classes work with one another.
圖3描述了主要的類是如何彼此工作的。


Figure 3. How animations are calculated

The ValueAnimator object keeps track of your animation's timing, such as how long the animation has been running, and the current value of the property that it is animating.
ValueAnimator對(duì)象保持追蹤你的動(dòng)畫的時(shí)間匠童,例如:這個(gè)動(dòng)畫已經(jīng)運(yùn)行了多久埂材,和它正在動(dòng)畫的屬性當(dāng)前的值。
The ValueAnimator encapsulates a TimeInterpolator, which defines animation interpolation, and a TypeEvaluator, which defines how to calculate values for the property being animated.
ValueAnimator封裝了一個(gè)TimeInterpolator汤求,它定義了動(dòng)畫插值俏险,和一個(gè)TypeEvaluator,它定義了如何計(jì)算將被動(dòng)畫的屬性的值扬绪。
For example, in Figure 2, the TimeInterpolator used would be AccelerateDecelerateInterpolator and the TypeEvaluator would be IntEvaluator.
例如竖独,在圖2中,使用的時(shí)間插值器將會(huì)是AccelerateDecelerateInterpolator挤牛,和類型計(jì)算器就將會(huì)是IntEvaluator莹痢。
To start an animation, create a ValueAnimator and give it the starting and ending values for the property that you want to animate, along with the duration of the animation.
為了開啟一個(gè)動(dòng)畫,創(chuàng)建一個(gè)ValueAnimator和賦予它的屬性你想要的動(dòng)畫的開始和結(jié)束的值,以及動(dòng)畫的持續(xù)時(shí)間墓赴。
When you call start() the animation begins.

當(dāng)你調(diào)用start()方法格二,動(dòng)畫開啟。
During the whole animation, the ValueAnimator calculates an elapsed fraction between 0 and 1, based on the duration of the animation and how much time has elapsed.
在整個(gè)動(dòng)畫中竣蹦,ValueAnimator計(jì)算在0和1之間的過去的分?jǐn)?shù)顶猜,基于動(dòng)畫的持續(xù)時(shí)間和經(jīng)過了多少時(shí)間。
The elapsed fraction represents the percentage of time that the animation has completed, 0 meaning 0% and 1 meaning 100%.
這個(gè)過去的分?jǐn)?shù)表現(xiàn)了動(dòng)畫完成的時(shí)間百分比痘括,0意味著0%和1意味著100%长窄。
For example, in Figure 1, the elapsed fraction at t = 10 ms would be .25 because the total duration is t = 40 ms.
例如,在圖1中纲菌,過去的分?jǐn)?shù)在t=10ms時(shí)將會(huì)是0.25挠日,因?yàn)榭偣渤掷m(xù)時(shí)間的時(shí)為t=40ms。
When the ValueAnimator is done calculating an elapsed fraction, it calls the TimeInterpolator that is currently set, to calculate an interpolated fraction.
當(dāng)ValueAnimator完成計(jì)算過去的分?jǐn)?shù)時(shí)翰舌,它將會(huì)調(diào)用當(dāng)前設(shè)置的TimeInterpolator嚣潜,去計(jì)算插值分?jǐn)?shù)。
An interpolated fraction maps the elapsed fraction to a new fraction that takes into account the time interpolation that is set.
內(nèi)插分?jǐn)?shù)將流逝分?jǐn)?shù)映射到考慮了設(shè)置的時(shí)間內(nèi)插的新分?jǐn)?shù)椅贱。
For example, in Figure 2, because the animation slowly accelerates, the interpolated fraction, about .15, is less than the elapsed fraction, .25, at t = 10 ms.
例如懂算,在圖2中虹曙,由于動(dòng)畫緩慢加速箫爷,因此在t = 10 ms時(shí)朗兵,插值分?jǐn)?shù)約為0.15翅帜,小于流逝分?jǐn)?shù).25。 在圖1中漓拾,內(nèi)插分?jǐn)?shù)總是與流逝分?jǐn)?shù)相同倔韭。
例如贝奇,在圖2中,由于動(dòng)畫緩慢加速睡雇,在t=10ms時(shí)刻萌衬,插值分?jǐn)?shù)約為0.15,小于流逝分?jǐn)?shù)0.25它抱。
In Figure 1, the interpolated fraction is always the same as the elapsed fraction.
在圖1中奄薇,插值分?jǐn)?shù)總是和消逝分?jǐn)?shù)相等。
When the interpolated fraction is calculated, ValueAnimator calls the appropriate TypeEvaluator, to calculate the value of the property that you are animating, based on the interpolated fraction, the starting value, and the ending value of the animation.
當(dāng)插值分?jǐn)?shù)被計(jì)算出來抗愁,ValueAnimator根據(jù)插值分?jǐn)?shù)、動(dòng)畫開始和結(jié)束的值呵晚,調(diào)用合適的TypeEvaluator去計(jì)算你正在動(dòng)畫的屬性的值蜘腌。
For example, in Figure 2, the interpolated fraction was .15 at t = 10 ms, so the value for the property at that time would be .15 X (40 - 0), or 6.
例如,在圖2中饵隙,在t=10ms時(shí)撮珠,插值分?jǐn)?shù)是0.15,所以此時(shí)屬性將會(huì)是0.15*(40-0)即6.
The com.example.android.apis.animation package in the API Demos sample project provides many examples on how to use the property animation system.
API Demos示例項(xiàng)目中的com.example.android.apis.animation包提供了許多有關(guān)如何使用屬性動(dòng)畫系統(tǒng)的示例金矛。

How Property Animation Differs from View Animation 屬性動(dòng)畫與View動(dòng)畫的差別

The view animation system provides the capability to only animate View objects, so if you wanted to animate non-View objects, you have to implement your own code to do so.
View動(dòng)畫系統(tǒng)提供了僅對(duì)View對(duì)象進(jìn)行動(dòng)畫處理的功能芯急。因此如果你想為非View對(duì)象設(shè)置動(dòng)畫效果,你不得不實(shí)現(xiàn)自己的代碼來執(zhí)行操作驶俊。
The view animation system is also constrained in the fact that it only exposes a few aspects of a View object to animate, such as the scaling and rotation of a View but not the background color, for instance.
View動(dòng)畫也受限于這樣一個(gè)事實(shí)娶耍,它僅暴露了View對(duì)象的一些方面,例如縮放和旋轉(zhuǎn)一個(gè)View饼酿,但是不包括背景顏色榕酒。
Another disadvantage of the view animation system is that it only modified where the View was drawn, and not the actual View itself.
視圖動(dòng)畫系統(tǒng)的另一個(gè)缺點(diǎn)是只能在視圖被繪制的地方進(jìn)行修改,而不是實(shí)際的視圖本身故俐。
For instance, if you animated a button to move across the screen, the button draws correctly, but the actual location where you can click the button does not change, so you have to implement your own logic to handle this.
例如想鹰,如果你使按鈕動(dòng)畫的穿過屏幕,按鈕被正確的繪制药版,但是事實(shí)上你點(diǎn)擊按鈕的位置卻沒有改變辑舷,所以你必須實(shí)現(xiàn)自己的邏輯來處理這個(gè)問題。
With the property animation system, these constraints are completely removed, and you can animate any property of any object (Views and non-Views) and the object itself is actually modified.
使用屬性動(dòng)畫系統(tǒng)槽片,這些約束被完全刪除何缓,并且可以為任何對(duì)象(視圖和非視圖)的任何屬性設(shè)置動(dòng)畫,并且對(duì)象本身實(shí)際上被修改还栓。
The property animation system is also more robust in the way it carries out animation.
動(dòng)畫屬性系統(tǒng)在執(zhí)行動(dòng)畫時(shí)也更加強(qiáng)壯歌殃。
At a high level, you assign animators to the properties that you want to animate, such as color, position, or size and can define aspects of the animation such as interpolation and synchronization of multiple animators.
從較高層次上講,你可以分配動(dòng)畫到你想要?jiǎng)赢嫷膶傩陨向疲珙伾ブ濉⑽恢谩⒒虼笮『涂梢远x動(dòng)畫的方面如:插值器和多個(gè)同步動(dòng)畫。
The view animation system, however, takes less time to setup and requires less code to write.
然而波材,View動(dòng)畫系統(tǒng)股淡,花費(fèi)更少的時(shí)間去設(shè)置和需要寫更少的代碼。
If view animation accomplishes everything that you need to do, or if your existing code already works the way you want, there is no need to use the property animation system.
如果動(dòng)畫完成了你需要執(zhí)行的所有事廷区,或者你已有的代碼已經(jīng)按照你想要的方式運(yùn)行唯灵,則無需使用屬性動(dòng)畫系統(tǒng)。
It also might make sense to use both animation systems for different situations if the use case arises.
如果出現(xiàn)用例隙轻,那么在不同情況下使用這兩種動(dòng)畫系統(tǒng)也是有意義的埠帕。

API Overview API總覽

Class Description
ValueAnimator The main timing engine for property animation that also computes the values for the property to be animated. It has all of the core functionality that calculates animation values and contains the timing details of each animation, information about whether an animation repeats, listeners that receive update events, and the ability to set custom types to evaluate. There are two pieces to animating properties: calculating the animated values and setting those values on the object and property that is being animated. ValueAnimator does not carry out the second piece, so you must listen for updates to values calculated by the ValueAnimator and modify the objects that you want to animate with your own logic. See the section about Animating with ValueAnimator for more information.
ObjectAnimator A subclass of ValueAnimator that allows you to set a target object and object property to animate. This class updates the property accordingly when it computes a new value for the animation. You want to use ObjectAnimator most of the time, because it makes the process of animating values on target objects much easier. However, you sometimes want to use ValueAnimator directly because ObjectAnimator has a few more restrictions, such as requiring specific acessor methods to be present on the target object.
AnimatorSet Provides a mechanism to group animations together so that they run in relation to one another. You can set animations to play together, sequentially, or after a specified delay. See the section about Choreographing multiple animations with Animator Sets for more information.

You can find most of the property animation system's APIs in android.animation.
你可以在android.animation中找到大部分屬性動(dòng)畫系統(tǒng)的API。
Because the view animation system already defines many interpolators in android.view.animation, you can use those interpolators in the property animation system as well.
由于View動(dòng)畫系統(tǒng)在android.view.animation中已經(jīng)定義了許多插值器玖绿,同樣你也可以在屬性動(dòng)畫中使用這些插值器敛瓷。
The following tables describe the main components of the property animation system.
接下來的這些介紹了屬性動(dòng)畫系統(tǒng)的主要的組件。
The Animator class provides the basic structure for creating animations.
Animator類提供了創(chuàng)建動(dòng)畫的基礎(chǔ)結(jié)構(gòu)斑匪。
You normally do not use this class directly as it only provides minimal functionality that must be extended to fully support animating values.
你通常不直接使用此類呐籽,因?yàn)樗惶峁┳钚〉墓δ埽仨殧U(kuò)展才能完全支持動(dòng)畫值蚀瘸。
The following subclasses extend Animator:
以下的子類繼承自Animator:
Table 1. Animators

Class Description
ValueAnimator The main timing engine for property animation that also computes the values for the property to be animated. It has all of the core functionality that calculates animation values and contains the timing details of each animation, information about whether an animation repeats, listeners that receive update events, and the ability to set custom types to evaluate. There are two pieces to animating properties: calculating the animated values and setting those values on the object and property that is being animated. ValueAnimator does not carry out the second piece, so you must listen for updates to values calculated by the ValueAnimator and modify the objects that you want to animate with your own logic. See the section about Animating with ValueAnimator for more information.
ObjectAnimator A subclass of ValueAnimator that allows you to set a target object and object property to animate. This class updates the property accordingly when it computes a new value for the animation. You want to use ObjectAnimator most of the time, because it makes the process of animating values on target objects much easier. However, you sometimes want to use ValueAnimator directly because ObjectAnimator has a few more restrictions, such as requiring specific acessor methods to be present on the target object.
AnimatorSet Provides a mechanism to group animations together so that they run in relation to one another. You can set animations to play together, sequentially, or after a specified delay. See the section about Choreographing multiple animations with Animator Sets for more information.
Class/Interface Description
IntEvaluator The default evaluator to calculate values for int properties.
FloatEvaluator The default evaluator to calculate values for float properties.
ArgbEvaluator The default evaluator to calculate values for color properties that are represented as hexidecimal values.
TypeEvaluator An interface that allows you to create your own evaluator. If you are animating an object property that is not an int, float, or color, you must implement the TypeEvaluator interface to specify how to compute the object property's animated values. You can also specify a custom TypeEvaluator for int, float, and color values as well, if you want to process those types differently than the default behavior. See the section about Using a TypeEvaluator for more information on how to write a custom evaluator.

Evaluators tell the property animation system how to calculate values for a given property.
Evaluators告訴屬性動(dòng)畫系統(tǒng)如何為給定的屬性計(jì)算值狡蝶。
They take the timing data that is provided by an Animator class, the animation's start and end value, and calculate the animated values of the property based on this data.
他們獲取Animator類提供的時(shí)間數(shù)據(jù),動(dòng)畫開始和終止的值贮勃,然后基于這些數(shù)據(jù)計(jì)算這個(gè)屬性的動(dòng)畫值贪惹。
The property animation system provides the following evaluators:
動(dòng)畫屬性系統(tǒng)提供一下Evaluators:
Table 2. Evaluators

Class/Interface Description
IntEvaluator The default evaluator to calculate values for int properties.
FloatEvaluator The default evaluator to calculate values for float properties.
ArgbEvaluator The default evaluator to calculate values for color properties that are represented as hexidecimal values.
TypeEvaluator An interface that allows you to create your own evaluator. If you are animating an object property that is not an int, float, or color, you must implement the TypeEvaluator interface to specify how to compute the object property's animated values. You can also specify a custom TypeEvaluator for int, float, and color values as well, if you want to process those types differently than the default behavior. See the section about Using a TypeEvaluator for more information on how to write a custom evaluator.
Class/Interface Description
AccelerateDecelerateInterpolator An interpolator whose rate of change starts and ends slowly but accelerates through the middle.
AccelerateInterpolator An interpolator whose rate of change starts out slowly and then accelerates.
AnticipateInterpolator An interpolator whose change starts backward then flings forward.一個(gè)插值器,其變化開始后向前閃爍寂嘉。
AnticipateOvershootInterpolator An interpolator whose change starts backward, flings forward and overshoots the target value, then finally goes back to the final value.
BounceInterpolator An interpolator whose change bounces at the end.內(nèi)插器的變化在最后反彈馍乙。
CycleInterpolator An interpolator whose animation repeats for a specified number of cycles.
DecelerateInterpolator An interpolator whose rate of change starts out quickly and then decelerates.
LinearInterpolator An interpolator whose rate of change is constant.
OvershootInterpolator An interpolator whose change flings forward and overshoots the last value then comes back.
TimeInterpolator An interface that allows you to implement your own interpolator.

A time interpolator defines how specific values in an animation are calculated as a function of time.
時(shí)間插值器定義動(dòng)畫中的特定值如何作為時(shí)間的函數(shù)進(jìn)行計(jì)算。
For example, you can specify animations to happen linearly across the whole animation, meaning the animation moves evenly the entire time, or you can specify animations to use non-linear time, for example, accelerating at the beginning and decelerating at the end of the animation.
舉個(gè)例子垫释,你可以指定動(dòng)畫在整個(gè)動(dòng)畫中線性發(fā)生丝格,意味著動(dòng)畫整個(gè)時(shí)間內(nèi)平均的移動(dòng),
或者你可以指定動(dòng)畫使用非線性時(shí)間棵譬,例如显蝌,在動(dòng)畫開始時(shí)加速和結(jié)束時(shí)減速。
Table 3 describes the interpolators that are contained in android.view.animation.
表3說明了包含在android.view.animation中的插值器订咸。
If none of the provided interpolators suits your needs, implement the TimeInterpolator interface and create your own.
如果提供的插值器沒有一個(gè)適合你使用曼尊,創(chuàng)建一個(gè)你自己的實(shí)現(xiàn)了TimeInterpolator接口插值器。
See Using interpolators for more information on how to write a custom interpolator.
查看使用插值器獲取更多關(guān)于如何寫一個(gè)自定義插值器的信息脏嚷。(有關(guān)如何編寫自定義插補(bǔ)器的更多信息骆撇,請(qǐng)參見使用插補(bǔ)器。 備注的是谷歌翻譯的父叙,谷歌翻譯就是牛逼)神郊。
Table 3. Interpolators

Class/Interface Description
AccelerateDecelerateInterpolator An interpolator whose rate of change starts and ends slowly but accelerates through the middle.
AccelerateInterpolator An interpolator whose rate of change starts out slowly and then accelerates.
AnticipateInterpolator An interpolator whose change starts backward then flings forward.一個(gè)插值器肴裙,其變化開始后向前閃爍。
AnticipateOvershootInterpolator An interpolator whose change starts backward, flings forward and overshoots the target value, then finally goes back to the final value.
BounceInterpolator An interpolator whose change bounces at the end.內(nèi)插器的變化在最后反彈涌乳。
CycleInterpolator An interpolator whose animation repeats for a specified number of cycles.
DecelerateInterpolator An interpolator whose rate of change starts out quickly and then decelerates.
LinearInterpolator An interpolator whose rate of change is constant.
OvershootInterpolator An interpolator whose change flings forward and overshoots the last value then comes back.
TimeInterpolator An interface that allows you to implement your own interpolator.

Animating with ValueAnimator 使用ValueAnimator進(jìn)行動(dòng)畫制作

The ValueAnimator class lets you animate values of some type for the duration of an animation by specifying a set of int, float, or color values to animate through.
通過指定一組int值蜻懦,浮點(diǎn)值或顏色值來設(shè)置動(dòng)畫效果,ValueAnimator類可以為動(dòng)畫的持續(xù)時(shí)間設(shè)置某種類型的值的動(dòng)畫夕晓。
You obtain a ValueAnimator by calling one of its factory methods: ofInt(), ofFloat(), or ofObject(). For example:
通過調(diào)用它的任一工廠方法:onInt()宛乃、ofFloat()、或者ofObject(),你可以獲取一個(gè)ValueAnimator蒸辆。例如:

ValueAnimator animation = ValueAnimator.ofFloat(0f, 100f);
animation.setDuration(1000);
animation.start();

In this code, the ValueAnimator starts calculating the values of the animation, between 0 and 100, for a duration of 1000 ms,when the start() method runs.
在這份代碼中征炼,當(dāng)start()方法運(yùn)行時(shí),ValueAnimator開始計(jì)算在0與100之間躬贡,持續(xù)時(shí)間為1000ms的動(dòng)畫的值谆奥。
You can also specify a custom type to animate by doing the following:
當(dāng)然你也可以通過執(zhí)行以下操作,指定一個(gè)自定義的類型來創(chuàng)建動(dòng)畫效果:

ValueAnimator animation = ValueAnimator.ofObject(new MyTypeEvaluator(), startPropertyValue, endPropertyValue);
animation.setDuration(1000);
animation.start();

In this code, the ValueAnimator starts calculating the values of the animation, between startPropertyValue and endPropertyValue using the logic supplied by MyTypeEvaluator for a duration of 1000 ms, when the start() method runs.
在這份代碼中逗宜,ValueAnimator開始使用MyTypeEvaluator提供的邏輯在startPropertyValue和endPropertyValue以及持續(xù)時(shí)間1000ms的條件下計(jì)算這個(gè)動(dòng)畫的值。

You can use the values of the animation by adding an AnimatorUpdateListener to the ValueAnimator object, as shown in the following code:
你可以使用這個(gè)動(dòng)畫的值通過給ValueAnimator來添加一個(gè)AnimatorUpdateListener空骚,如以下代碼展示的這樣纺讲。

animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator updatedAnimation) {
        // You can use the animated value in a property that uses the
        // same type as the animation. In this case, you can use the
        // float value in the translationX property.
        float animatedValue = (float)updatedAnimation.getAnimatedValue();
        textView.setTranslationX(animatedValue);
    }
});

In the onAnimationUpdate() method you can access the updated animation value and use it in a property of one of your views. For more information on listeners, see the section about Animation Listeners
在onAnimationUpdate()方法中囤屹,你可以訪問更新后的動(dòng)畫值熬甚,并將其用于其中一個(gè)視圖的屬性中。

Animating with ObjectAnimator 使用ObjectAnimator創(chuàng)建動(dòng)畫

The ObjectAnimator is a subclass of the ValueAnimator (discussed in the previous section) and combines the timing engine and value computation of ValueAnimator with the ability to animate a named property of a target object.
ObjectAnimator是ValueAnimator的一個(gè)子類(在上一節(jié)中討論過)肋坚,它將ValueAnimator的時(shí)序引擎和值計(jì)算與對(duì)目標(biāo)對(duì)象的命名屬性進(jìn)行動(dòng)畫處理的功能相結(jié)合乡括。
This makes animating any object much easier, as you no longer need to implement the ValueAnimator.AnimatorUpdateListener, because the animated property updates automatically.
這使得任何對(duì)象的動(dòng)畫更容易,因?yàn)槟悴辉傩枰獙?shí)現(xiàn)ValueAnimator.AnimatorUpdateListener智厌,因?yàn)閯?dòng)畫屬性會(huì)自動(dòng)更新诲泌。
Instantiating an ObjectAnimator is similar to a ValueAnimator, but you also specify the object and the name of that object's property (as a String) along with the values to animate between:
實(shí)例化一個(gè)ObjectAnimator類似于一個(gè)ValueAnimator,但是你還需要指定該對(duì)象的屬性名稱(作為字符串)以及值之間進(jìn)行動(dòng)畫處理:

ObjectAnimator animation = ObjectAnimator.ofFloat(textView, "translationX", 100f);
animation.setDuration(1000);
animation.start();

To have the ObjectAnimator update properties correctly, you must do the following:
要正確的更新ObjectAnimator屬性铣鹏,你必須執(zhí)行以下操作:

  • The object property that you are animating must have a setter function (in camel case) in the form of set<PropertyName>(). Because the ObjectAnimator automatically updates the property during animation, it must be able to access the property with this setter method. For example, if the property name is foo, you need to have a setFoo() method.
    你正在設(shè)置動(dòng)畫的對(duì)象屬性必須以set()的形式具有setter函數(shù)(駱駝大小寫)敷扫。 由于ObjectAnimator在動(dòng)畫期間自動(dòng)更新屬性,因此必須能夠使用此setter方法訪問屬性诚卸。 例如葵第,如果屬性名稱是foo,則需要有一個(gè)setFoo()方法合溺。
    If this setter method does not exist, you have three options:
    如果setter方法不存在卒密,你擁有以下三個(gè)選擇:
    • Add the setter method to the class if you have the rights to do so.在這個(gè)類中添加setter方法,如果你有權(quán)限這樣做棠赛。
    • Use a wrapper class that you have rights to change and have that wrapper receive the value with a valid setter method and forward it to the original object.使用你有權(quán)修改的包裝類哮奇,并讓該包裝接收有效的setter方法的值并將其轉(zhuǎn)發(fā)給原始對(duì)象膛腐。
    • Use ValueAnimator instead.使用ValueAnimator替代
  • If you specify only one value for the values... parameter in one of the ObjectAnimator factory methods, it is assumed to be the ending value of the animation. Therefore, the object property that you are animating must have a getter function that is used to obtain the starting value of the animation. The getter function must be in the form of get<PropertyName>(). For example, if the property name is foo, you need to have a getFoo() method.如果你在其中一個(gè)ObjectAnimator工廠方法中為values ...參數(shù)指定了僅一個(gè)值,則它被假定為動(dòng)畫的結(jié)束值屏镊。 因此依疼,你正在動(dòng)畫的對(duì)象屬性必須具有用于獲取動(dòng)畫起始值的getter函數(shù)。 getter函數(shù)必須采用get <PropertyName>()的形式而芥。 例如律罢,如果屬性名稱是foo,則需要有一個(gè)getFoo()方法棍丐。
  • The getter (if needed) and setter methods of the property that you are animating must operate on the same type as the starting and ending values that you specify to ObjectAnimator. For example, you must have targetObject.setPropName(float) and targetObject.getPropName(float) if you construct the following ObjectAnimator:你要?jiǎng)赢嫷膶傩缘膅etter(如果需要)和setter方法必須以與指定給ObjectAnimator的開始和結(jié)束值相同的類型進(jìn)行操作误辑。 例如,如果構(gòu)造以下ObjectAnimator歌逢,則必須具有targetObject.setPropName(float)和targetObject.getPropName(float):
ObjectAnimator.ofFloat(targetObject, "propName", 1f)
  • Depending on what property or object you are animating, you might need to call the invalidate() method on a View to force the screen to redraw itself with the updated animated values. You do this in the onAnimationUpdate() callback. For example, animating the color property of a Drawable object only causes updates to the screen when that object redraws itself. All of the property setters on View, such as setAlpha() and setTranslationX() invalidate the View properly, so you do not need to invalidate the View when calling these methods with new values. For more information on listeners, see the section about Animation Listeners.根據(jù)你要?jiǎng)赢嫷膶傩曰驅(qū)ο蠼矶ぃ憧赡苄枰谝晥D上調(diào)用invalidate()方法以強(qiáng)制屏幕使用更新的動(dòng)畫值重繪本身。 你可以在onAnimationUpdate()回調(diào)中執(zhí)行此操作秘案。 例如砰苍,對(duì)Drawable對(duì)象的顏色屬性進(jìn)行動(dòng)畫處理只會(huì)導(dǎo)致該對(duì)象重繪時(shí)自動(dòng)更新屏幕。View所有的屬性設(shè)置器阱高,例如setAlpha()和setTranslationX()都會(huì)正確的廢止View,因此當(dāng)調(diào)用這些方法時(shí)赚导,你不需要使View無效。有關(guān)偵聽器的更多信息赤惊,請(qǐng)參閱關(guān)于動(dòng)畫偵聽器的部分吼旧。

Choreographing Multiple Animations with AnimatorSet 用AnimatorSet編排多個(gè)動(dòng)畫

In many cases, you want to play an animation that depends on when another animation starts or finishes.
在許多情況下,你想播放取決于另外一個(gè)動(dòng)畫的開始或結(jié)束的動(dòng)畫未舟。
The Android system lets you bundle animations together into an AnimatorSet, so that you can specify whether to start animations simultaneously, sequentially, or after a specified delay. You can also nest AnimatorSet objects within each other.
Android系統(tǒng)讓你將動(dòng)畫捆綁到一個(gè)AnimatorSet中圈暗,以便你指定動(dòng)畫立刻、按照順序裕膀、或者在一個(gè)特定的延遲開始播放员串。你也可以將AnimatorSet對(duì)象嵌套在對(duì)方內(nèi)。
The following sample code taken from the Bouncing Balls sample (modified for simplicity) plays the following Animator objects in the following manner:
接下來摘自Bouncing Balls示例(簡(jiǎn)單修改)的示例代碼按以下方式播放以下Animator對(duì)象:

  1. Plays bounceAnim.
  2. Plays squashAnim1, squashAnim2, stretchAnim1, and stretchAnim2 at the same time.
  3. Plays bounceBackAnim.
  4. Plays fadeAnim.
AnimatorSet bouncer = new AnimatorSet();
bouncer.play(bounceAnim).before(squashAnim1);
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
bouncer.play(squashAnim1).with(stretchAnim2);
bouncer.play(bounceBackAnim).after(stretchAnim2);
ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(bouncer).before(fadeAnim);
animatorSet.start();

For a more complete example on how to use animator sets, see the Bouncing Balls sample in APIDemos.
關(guān)于如何使用animator集合更完整的示例昼扛,請(qǐng)查看在APIDemos中的Bouncing Balls示例昵济。

Animation Listeners 動(dòng)畫偵聽者

You can listen for important events during an animation's duration with the listeners described below.
在動(dòng)畫持續(xù)時(shí)間內(nèi),你可以偵聽以下描述的偵聽器中的重要事件野揪。

  • Animator.AnimatorListener
    • onAnimationStart() - Called when the animation starts.
    • onAnimationEnd() - Called when the animation ends.
    • onAnimationRepeat() - Called when the animation repeats itself.
    • onAnimationCancel() - Called when the animation is canceled. A cancelled animation also calls onAnimationEnd(), regardless of how they were ended.
  • ValueAnimator.AnimatorUpdateListener
    • onAnimationUpdate() - called on every frame of the animation. Listen to this event to use the calculated values generated by ValueAnimator during an animation. To use the value, query the ValueAnimator object passed into the event to get the current animated value with the getAnimatedValue() method. Implementing this listener is required if you use ValueAnimator.
      Depending on what property or object you are animating, you might need to call invalidate() on a View to force that area of the screen to redraw itself with the new animated values. For example, animating the color property of a Drawable object only cause updates to the screen when that object redraws itself. All of the property setters on View, such as setAlpha() and setTranslationX() invalidate the View properly, so you do not need to invalidate the View when calling these methods with new values.

Animating Layout Changes to ViewGroups 動(dòng)畫布局更改為ViewGroups

The property animation system provides the capability to animate changes to ViewGroup objects as well as provide an easy way to animate View objects themselves.
屬性動(dòng)畫系統(tǒng)提供了對(duì)ViewGroup對(duì)象進(jìn)行動(dòng)畫變化的功能访忿,并提供了一種簡(jiǎn)單的方法來為View對(duì)象本身制作動(dòng)畫。
You can animate layout changes within a ViewGroup with the LayoutTransition class.
你可以使用LayoutTransition類對(duì)ViewGroup中的布局更改進(jìn)行動(dòng)畫處理斯稳。
Views inside a ViewGroup can go through an appearing and disappearing animation when you add them to or remove them from a ViewGroup or when you call a View's setVisibility() method with VISIBLE, INVISIBLE, or GONE.
ViewGroup中的視圖可以在將ViewGroup添加到ViewGroup中或從ViewGroup中刪除它們時(shí)海铆,或者當(dāng)你使用VISIBLE,INVISIBLE或GONE調(diào)用View的setVisibility()方法時(shí)挣惰,經(jīng)過出現(xiàn)和消失的動(dòng)畫卧斟。
The remaining Views in the ViewGroup can also animate into their new positions when you add or remove Views.
當(dāng)添加或刪除視圖時(shí)殴边,ViewGroup中的其余視圖也可以動(dòng)畫到他們的新位置。
You can define the following animations in a LayoutTransition object by calling setAnimator() and passing in an Animator object with one of the following LayoutTransition constants:
你可以通過調(diào)用setAnimator()并使用下列LayoutTransition常量之一傳入Animator對(duì)象來在LayoutTransition對(duì)象中定義以下動(dòng)畫:

  • APPEARING - A flag indicating the animation that runs on items that are appearing in the container.
    CHANGE_APPEARING - A flag indicating the animation that runs on items that are changing due to a new item appearing in the container.
  • DISAPPEARING - A flag indicating the animation that runs on items that are disappearing from the container.
  • CHANGE_DISAPPEARING - A flag indicating the animation that runs on items that are changing due to an item disappearing from the container.

You can define your own custom animations for these four types of events to customize the look of your layout transitions or just tell the animation system to use the default animations.
你可以為這四種類型的事件定義自己的自定義動(dòng)畫珍语,以自定義布局轉(zhuǎn)換的外觀锤岸,或者僅告訴動(dòng)畫系統(tǒng)使用默認(rèn)動(dòng)畫。

The LayoutAnimations sample in API Demos shows you how to define animations for layout transitions and then set the animations on the View objects that you want to animate.
API演示中的LayoutAnimations示例向你展示了如何為布局轉(zhuǎn)換定義動(dòng)畫板乙,然后在你想要制作動(dòng)畫的視圖對(duì)象上設(shè)置動(dòng)畫是偷。
The LayoutAnimationsByDefault and its corresponding layout_animations_by_default.xml layout resource file show you how to enable the default layout transitions for ViewGroups in XML. The only thing that you need to do is to set the android:animateLayoutchanges attribute to true for the ViewGroup. For example:
LayoutAnimationsByDefault及其相應(yīng)的layout_animations_by_default.xml布局資源文件顯示如何為XML中的ViewGroups啟用默認(rèn)布局轉(zhuǎn)換。 唯一需要做的就是將ViewGroup的android:animateLayoutchanges屬性設(shè)置為true募逞。 例如:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/verticalContainer"
    android:animateLayoutChanges="true" />

Setting this attribute to true automatically animates Views that are added or removed from the ViewGroup as well as the remaining Views in the ViewGroup.
將此屬性設(shè)置為true會(huì)自動(dòng)生成從ViewGroup添加或刪除的視圖以及ViewGroup中剩余的視圖蛋铆。

Using StateListAnimator to animate view state changes 使用StateListAnimator創(chuàng)建視圖狀態(tài)變更動(dòng)畫

The StateListAnimator class lets you define animators that run when the state of a view changes.
StateListAnimator類允許你定義在View的狀態(tài)變化時(shí)運(yùn)行的動(dòng)畫。
This object behaves as a wrapper for an Animator object, calling that animation whenever the specified view state (such as "pressed" or "focused") changes.
該對(duì)象充當(dāng)動(dòng)畫對(duì)象的包裝器放接,每當(dāng)指定的視圖狀態(tài)(如“按下”或“焦點(diǎn)”)更改時(shí)調(diào)用該動(dòng)畫刺啦。
The StateListAnimator can be defined in an XML resource with a root <selector> element and child <item> elements that each specify a different view state defined by the StateListAnimator class.
StateListAnimator可以在具有根<selector>元素和子元素<item>的XML資源中定義,每個(gè)子元素指定由StateListAnimator類定義的不同視圖狀態(tài)纠脾。
Each <item> contains the definition for a property animation set.
每一個(gè)<item>包含這個(gè)屬性動(dòng)畫集合的定義玛瘸。
For example, the following file creates a state list animator that changes the x and y scale of the view when it's pressed:
舉個(gè)栗子,下面的文件創(chuàng)建了一個(gè)狀態(tài)列表動(dòng)畫器苟蹈,用于當(dāng)視圖被按壓時(shí)改變它的x和y的比例糊渊。
res/xml/animate_scale.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- the pressed state; increase x and y size to 150% -->
    <item android:state_pressed="true">
        <set>
            <objectAnimator android:propertyName="scaleX"
                android:duration="@android:integer/config_shortAnimTime"
                android:valueTo="1.5"
                android:valueType="floatType"/>
            <objectAnimator android:propertyName="scaleY"
                android:duration="@android:integer/config_shortAnimTime"
                android:valueTo="1.5"
                android:valueType="floatType"/>
        </set>
    </item>
    <!-- the default, non-pressed state; set x and y size to 100% -->
    <item android:state_pressed="false">
        <set>
            <objectAnimator android:propertyName="scaleX"
                android:duration="@android:integer/config_shortAnimTime"
                android:valueTo="1"
                android:valueType="floatType"/>
            <objectAnimator android:propertyName="scaleY"
                android:duration="@android:integer/config_shortAnimTime"
                android:valueTo="1"
                android:valueType="floatType"/>
        </set>
    </item>
</selector>

To attach the state list animator to a view, add the android:stateListAnimator attribute as follows:
要將狀態(tài)列表動(dòng)畫添加到視圖,請(qǐng)按如下所示添加android:stateListAnimator屬性:

<Button android:stateListAnimator="@xml/animate_scale"
        ... />

Now the animations defined in animate_scale.xml are used when this button's state changes.
當(dāng)這個(gè)按鈕的狀態(tài)改變汉操,當(dāng)前定義在animate_scale.xml動(dòng)畫被使用再来。
Or to instead assign a state list animator to a view in your code, use the AnimatorInflater.loadStateListAnimator() method, and assign the animator to your view with the View.setStateListAnimator() method.
或者改為將狀態(tài)列表動(dòng)畫器分配給代碼中的視圖蒙兰,請(qǐng)使用AnimatorInflater.loadStateListAnimator()方法磷瘤,并使用View.setStateListAnimator()方法將動(dòng)畫器分配給視圖。
Or instead of animating properties of the view, you can play a drawable animation between state changes, using AnimatedStateListDrawable.
或者搜变,你可以使用AnimatedStateListDrawable在狀態(tài)更改之間播放可繪制動(dòng)畫采缚,而不是動(dòng)畫視圖的屬性。
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:
Android 5.0中的一些系統(tǒng)小部件默認(rèn)使用這些動(dòng)畫挠他。 以下示例顯示如何將AnimatedStateListDrawable定義為XML資源:

<!-- 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>

Using a TypeEvaluator 使用TypeEvaluator

If you want to animate a type that is unknown to the Android system, you can create your own evaluator by implementing the TypeEvaluator interface.
如果你為一個(gè)Android系統(tǒng)不知道的類型創(chuàng)建動(dòng)畫扳抽,你可以通過實(shí)現(xiàn)TypeEvaluator接口創(chuàng)建你自己的Evaluator。
The types that are known by the Android system are int, float, or a color, which are supported by the IntEvaluator, FloatEvaluator, and ArgbEvaluator type evaluators.
Android系統(tǒng)所熟知的類型是int殖侵,float或color贸呢,它們通過IntEvaluator,F(xiàn)loatEvaluator和ArgbEvaluator類型Evaluator拢军。
There is only one method to implement in the TypeEvaluator interface, the evaluate() method.
在TypeEvaluator接口中只有一個(gè)方法需要執(zhí)行evaluate()方法楞陷。
This allows the animator that you are using to return an appropriate value for your animated property at the current point of the animation.
這允許你正在使用的動(dòng)畫在動(dòng)畫當(dāng)前點(diǎn)為你的動(dòng)畫屬性返回適當(dāng)?shù)闹怠?br> The FloatEvaluator class demonstrates how to do this:
FloatEvaluator類演示了如何執(zhí)行此操作:

public class FloatEvaluator implements TypeEvaluator {

    public Object evaluate(float fraction, Object startValue, Object endValue) {
        float startFloat = ((Number) startValue).floatValue();
        return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);
    }
}

Note: When ValueAnimator (or ObjectAnimator) runs, it calculates a current elapsed fraction of the animation (a value between 0 and 1) and then calculates an interpolated version of that depending on what interpolator that you are using. The interpolated fraction is what your TypeEvaluator receives through the fraction parameter, so you do not have to take into account the interpolator when calculating animated values.
注意:當(dāng)ValueAnimator(或ObjectAnimator)運(yùn)行時(shí),它會(huì)計(jì)算動(dòng)畫當(dāng)前流逝的部分(介于0和1之間的一個(gè)值)茉唉,然后根據(jù)你使用的插值器計(jì)算插值版本固蛾。內(nèi)插分?jǐn)?shù)是TypeEvaluator通過分?jǐn)?shù)參數(shù)接收的值结执,因此計(jì)算動(dòng)畫值時(shí)不必考慮插值器。

Using Interpolators 使用插值器

An interpolator define how specific values in an animation are calculated as a function of time.
插值器定義了在動(dòng)畫中特定值是如何作為時(shí)間的函數(shù)進(jìn)行計(jì)算的艾凯。
For example, you can specify animations to happen linearly across the whole animation, meaning the animation moves evenly the entire time, or you can specify animations to use non-linear time, for example, using acceleration or deceleration at the beginning or end of the animation.
舉個(gè)例子献幔,你可以指定動(dòng)畫在整個(gè)動(dòng)畫中線性發(fā)生,意味著動(dòng)畫整個(gè)時(shí)間內(nèi)平均的移動(dòng)趾诗,或者你可以指定動(dòng)畫使用非線性時(shí)間蜡感,例如,在動(dòng)畫開始時(shí)加速和結(jié)束時(shí)減速沧竟。
Interpolators in the animation system receive a fraction from Animators that represent the elapsed time of the animation.
動(dòng)畫系統(tǒng)中的插值器會(huì)接收來自動(dòng)畫器的分?jǐn)?shù)铸敏,表示動(dòng)畫已用時(shí)間。
Interpolators modify this fraction to coincide with the type of animation that it aims to provide.
插值器修改此分?jǐn)?shù)以符合它旨在提供的動(dòng)畫類型悟泵。
The Android system provides a set of common interpolators in the android.view.animation package.
Android系統(tǒng)在android.view.animation包中提供一組常用的插值算法杈笔。
If none of these suit your needs, you can implement the TimeInterpolator interface and create your own.
如果這些都不符合你的需求,你可以實(shí)現(xiàn)TimeInterpolator接口并創(chuàng)建你自己的糕非。
As an example, how the default interpolator AccelerateDecelerateInterpolator and the LinearInterpolator calculate interpolated fractions are compared below.
例如蒙具,下面比較默認(rèn)插值器AccelerateDecelerateInterpolator和LinearInterpolator計(jì)算插值分?jǐn)?shù)的方式。
The LinearInterpolator has no effect on the elapsed fraction. The AccelerateDecelerateInterpolator accelerates into the animation and decelerates out of it. The following methods define the logic for these interpolators:
LinearInterpolator對(duì)經(jīng)過的分?jǐn)?shù)沒有影響朽肥。 AccelerateDecelerateInterpolator加速進(jìn)入動(dòng)畫并減速禁筏。 以下方法定義了這些內(nèi)插器的邏輯:
AccelerateDecelerateInterpolator

public float getInterpolation(float input) {
    return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}

LinearInterpolator

public float getInterpolation(float input) {
    return input;
}
ms elapsed Elapsed fraction/Interpolated fraction (Linear) Interpolated fraction (Accelerate/Decelerate)
0 0 0
200 .2 .1
400 .4 .345
600 .6 .8
800 .8 .9
1000 1 1

The following table represents the approximate values that are calculated by these interpolators for an animation that lasts 1000ms:
下表表示這些插補(bǔ)器對(duì)持續(xù)1000毫秒的動(dòng)畫計(jì)算的近似值:

ms elapsed Elapsed fraction/Interpolated fraction (Linear) Interpolated fraction (Accelerate/Decelerate)
0 0 0
200 .2 .1
400 .4 .345
600 .6 .8
800 .8 .9
1000 1 1

As the table shows, the LinearInterpolator changes the values at the same speed, .2 for every 200ms that passes.
如表所示,LinearInterpolator以相同的速度更改值衡招,每200ms傳遞一次篱昔。
The AccelerateDecelerateInterpolator changes the values faster than LinearInterpolator between 200ms and 600ms and slower between 600ms and 1000ms.
AccelerateDecelerateInterpolator在200ms和600ms之間比LinearInterpolator更快地改值,在600ms和1000ms之間慢一些始腾。

Specifying Keyframes 指定關(guān)鍵幀

A Keyframe object consists of a time/value pair that lets you define a specific state at a specific time of an animation.
一個(gè)Keyframe對(duì)象由一個(gè)時(shí)間/值對(duì)組成州刽,它允許你在動(dòng)畫的特定時(shí)間定義特定的狀態(tài)。
Each keyframe can also have its own interpolator to control the behavior of the animation in the interval between the previous keyframe's time and the time of this keyframe.
每個(gè)關(guān)鍵幀還可以有自己的插補(bǔ)器浪箭,以控制前一個(gè)關(guān)鍵幀時(shí)間與該關(guān)鍵幀時(shí)間之間的間隔內(nèi)的動(dòng)畫行為穗椅。
To instantiate a Keyframe object, you must use one of the factory methods, ofInt(), ofFloat(), or ofObject() to obtain the appropriate type of Keyframe.
要實(shí)例化一個(gè)Keyframe對(duì)象,必須使用工廠方法之一的Int()奶栖,ofFloat()或ofObject()來獲取適當(dāng)類型的Keyframe匹表。
You then call the ofKeyframe() factory method to obtain a PropertyValuesHolder object.
然后調(diào)用ofKeyframe()工廠方法來獲取PropertyValuesHolder對(duì)象。
Once you have the object, you can obtain an animator by passing in the PropertyValuesHolder object and the object to animate.
獲得對(duì)象后宣鄙,可以通過傳遞PropertyValuesHolder對(duì)象和對(duì)象來獲取動(dòng)畫袍镀。
The following code snippet demonstrates how to do this:
以下代碼片段演示了如何執(zhí)行此操作:

Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
Keyframe kf1 = Keyframe.ofFloat(.5f, 360f);
Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation)
rotationAnim.setDuration(5000ms);

For a more complete example on how to use keyframes, see the MultiPropertyAnimation sample in APIDemos.

Animating Views

The property animation system allow streamlined animation of View objects and offers a few advantages over the view animation system.
屬性動(dòng)畫系統(tǒng)允許View對(duì)象的簡(jiǎn)化動(dòng)畫,并且與視圖動(dòng)畫系統(tǒng)相比具有一些優(yōu)點(diǎn)冻晤。
The view animation system transformed View objects by changing the way that they were drawn.
視圖動(dòng)畫系統(tǒng)通過改變它們被繪制的方式來轉(zhuǎn)換視圖對(duì)象苇羡。
This was handled in the container of each View, because the View itself had no properties to manipulate.
這是在每個(gè)視圖的容器中處理的,因?yàn)橐晥D本身沒有可操作的屬性明也。
This resulted in the View being animated, but caused no change in the View object itself. This led to behavior such as an object still existing in its original location, even though it was drawn on a different location on the screen.
這導(dǎo)致視圖被動(dòng)畫宣虾,但在視圖對(duì)象本身中沒有改變惯裕。 這導(dǎo)致行為,例如對(duì)象仍然存在于其原始位置绣硝,即使它是在屏幕上的不同位置繪制的蜻势。
In Android 3.0, new properties and the corresponding getter and setter methods were added to eliminate this drawback.
在Android 3.0中,添加了新的屬性和相應(yīng)的getter和setter方法來消除這個(gè)缺點(diǎn)鹉胖。
The property animation system can animate Views on the screen by changing the actual properties in the View objects.
屬性動(dòng)畫系統(tǒng)可以通過改變視圖對(duì)象中的實(shí)際屬性來在屏幕上動(dòng)畫視圖握玛。
In addition, Views also automatically call the invalidate() method to refresh the screen whenever its properties are changed.
另外,視圖也會(huì)自動(dòng)調(diào)用invalidate()方法刷新屏幕甫菠,只要其屬性發(fā)生更改挠铲。
The new properties in the View class that facilitate property animations are:
有助于屬性動(dòng)畫的View類中的新屬性是:

  • translationX and translationY: These properties control where the View is located as a delta from its left and top coordinates which are set by its layout container.
  • rotation, rotationX, and rotationY: These properties control the rotation in 2D (rotation property) and 3D around the pivot point.
  • scaleX and scaleY: These properties control the 2D scaling of a View around its pivot point.
  • pivotX and pivotY: These properties control the location of the pivot point, around which the rotation and scaling transforms occur. By default, the pivot point is located at the center of the object.
  • x and y: These are simple utility properties to describe the final location of the View in its container, as a sum of the left and top values and translationX and translationY values.
  • alpha: Represents the alpha transparency on the View. This value is 1 (opaque) by default, with a value of 0 representing full transparency (not visible).

To animate a property of a View object, such as its color or rotation value, all you need to do is create a property animator and specify the View property that you want to animate. For example:
要為View對(duì)象的屬性(例如其顏色或旋轉(zhuǎn)值)設(shè)置動(dòng)畫效果寂诱,你只需創(chuàng)建屬性動(dòng)畫器并指定要設(shè)置動(dòng)畫效果的View屬性即可痰洒。舉個(gè)栗子:

ObjectAnimator.ofFloat(myView, "rotation", 0f, 360f);

For more information on creating animators, see the sections on animating with ValueAnimator and ObjectAnimator.
有關(guān)創(chuàng)建動(dòng)畫的更多信息瓢棒,請(qǐng)參閱關(guān)于使用ValueAnimatorObjectAnimator進(jìn)行動(dòng)畫制作的章節(jié)丘喻。

Animating with ViewPropertyAnimator 通過ViewPropertyAnimator創(chuàng)建動(dòng)畫

The ViewPropertyAnimator provides a simple way to animate several properties of a View in parallel, using a single underlying Animator object.
ViewPropertyAnimator提供了一種簡(jiǎn)單的方法,可以使用單個(gè)基礎(chǔ)Animator對(duì)象并行地對(duì)View的幾個(gè)屬性進(jìn)行動(dòng)畫處理泉粉。
It behaves much like an ObjectAnimator, because it modifies the actual values of the view's properties, but is more efficient when animating many properties at once.
它的行為與ObjectAnimator非常相似,因?yàn)樗薷牧艘晥D屬性的實(shí)際值跺撼,但在同時(shí)動(dòng)畫多個(gè)屬性時(shí)效率更高财边。
In addition, the code for using the ViewPropertyAnimator is much more concise and easier to read.
此外,使用ViewPropertyAnimator的代碼更加簡(jiǎn)潔易讀黑滴。
The following code snippets show the differences in using multiple ObjectAnimator objects, a single ObjectAnimator, and the ViewPropertyAnimator when simultaneously animating the x and y property of a view.
以下代碼片段顯示了在同時(shí)為視圖的x和y屬性設(shè)置動(dòng)畫時(shí)袁辈,使用多個(gè)ObjectAnimator對(duì)象晚缩,單個(gè)ObjectAnimator和ViewPropertyAnimator的差異荞彼。
Multiple ObjectAnimator objects

ObjectAnimator animX = ObjectAnimator.ofFloat(myView, "x", 50f);
ObjectAnimator animY = ObjectAnimator.ofFloat(myView, "y", 100f);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();

One ObjectAnimator

PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();

ViewPropertyAnimator

myView.animate().x(50f).y(100f);

For more detailed information about ViewPropertyAnimator, see the corresponding Android Developers blog post.

Declaring Animations in XML 在XML中聲明動(dòng)畫

The property animation system lets you declare property animations with XML instead of doing it programmatically.
屬性動(dòng)畫系統(tǒng)允許你用XML聲明屬性動(dòng)畫惠呼,而不是以編程方式進(jìn)行。
By defining your animations in XML, you can easily reuse your animations in multiple activities and more easily edit the animation sequence.
通過用XML定義動(dòng)畫,你可以輕松地在多個(gè)活動(dòng)中重復(fù)使用動(dòng)畫滩届,并更輕松地編輯動(dòng)畫序列丐吓。
To distinguish animation files that use the new property animation APIs from those that use the legacy view animation framework, starting with Android 3.1, you should save the XML files for property animations in the res/animator/ directory.
為了將使用新屬性動(dòng)畫API的動(dòng)畫文件與使用舊視圖動(dòng)畫框架的動(dòng)畫文件區(qū)分開來券犁,從Android 3.1開始粘衬,應(yīng)該將屬性動(dòng)畫的XML文件保存在res/animator/目錄中稚新。
The following property animation classes have XML declaration support with the following XML tags:
以下屬性動(dòng)畫類使用以下XML標(biāo)記支持XML聲明:

  • ValueAnimator - <animator>
  • ObjectAnimator - <objectAnimator>
  • AnimatorSet - <set>
    To find the attributes that you can use in your XML declaration, see Animation Resources.
    為了找到你可以在XML中使用的屬性褂删,請(qǐng)查看Animation Resources屯阀。
    The following example plays the two sets of object animations sequentially, with the first nested set playing two object animations together:
    接下來的例子順序的播放了兩個(gè)對(duì)象動(dòng)畫組合难衰,第一個(gè)嵌套集合一起播放兩個(gè)對(duì)象動(dòng)畫:
<set android:ordering="sequentially">
    <set>
        <objectAnimator
            android:propertyName="x"
            android:duration="500"
            android:valueTo="400"
            android:valueType="intType"/>
        <objectAnimator
            android:propertyName="y"
            android:duration="500"
            android:valueTo="300"
            android:valueType="intType"/>
    </set>
    <objectAnimator
        android:propertyName="alpha"
        android:duration="500"
        android:valueTo="1f"/>
</set>

In order to run this animation, you must inflate the XML resources in your code to an AnimatorSet object, and then set the target objects for all of the animations before starting the animation set.
為了運(yùn)行此動(dòng)畫,你必須將代碼中的XML資源充入AnimatorSet對(duì)象鳄虱,然后在開始動(dòng)畫設(shè)置之前為所有動(dòng)畫設(shè)置目標(biāo)對(duì)象拙已。
Calling setTarget() sets a single target object for all children of the AnimatorSet as a convenience. The following code shows how to do this:
為方便起見悠栓,調(diào)用setTarget()為AnimatorSet的所有子節(jié)點(diǎn)設(shè)置一個(gè)目標(biāo)對(duì)象惭适。 以下代碼顯示了如何執(zhí)行此操作:

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext,
    R.anim.property_animator);
set.setTarget(myObject);
set.start();

You can also declare a ValueAnimator in XML, as shown in the following example:
你也可以定ValueAnimator在XML中癞志,如以下示例所示:

<animator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:valueType="floatType"
    android:valueFrom="0f"
    android:valueTo="-100f" />

To use the previous ValueAnimator in your code, you must inflate the object, add an AnimatorUpdateListener, get the updated animation value, and use it in a property of one of your views, as shown in the following code:
要在代碼中使用以前的ValueAnimator凄杯,你必須膨脹對(duì)象屯碴,添加AnimatorUpdateListener导而,獲取更新后的動(dòng)畫值今艺,并將其用于你的某個(gè)視圖的屬性中虚缎,如以下代碼所示:

ValueAnimator xmlAnimator = (ValueAnimator) AnimatorInflater.loadAnimator(this,
        R.animator.animator);
xmlAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator updatedAnimation) {
        float animatedValue = (float)updatedAnimation.getAnimatedValue();
        textView.setTranslationX(animatedValue);
    }
});

xmlAnimator.start();

For information about the XML syntax for defining property animations, see Animation Resources .
有關(guān)定義屬性動(dòng)畫的XML語法的信息实牡,請(qǐng)參閱動(dòng)畫資源铲掐。

Implications for UI performance 對(duì)UI性能的影響

Animators that update the UI cause extra rendering work for every frame in which the animation runs. For this reason, using resource intensive animations can negatively impact the performance of your app.
更新UI的動(dòng)畫器會(huì)為動(dòng)畫運(yùn)行的每個(gè)幀導(dǎo)致額外的渲染工作豪椿。 因此携栋,使用資源密集型動(dòng)畫可能會(huì)對(duì)應(yīng)用程序的性能產(chǎn)生負(fù)面影響。

Work required to animate your UI is added to the animation stage of the rendering pipeline. You can find out if your animations impact the performance of your app by enabling Profile GPU Rendering and monitoring the animation stage. For more information, see Profile GPU Rendering Walkthrough.
將渲染UI的動(dòng)畫添加到渲染管道的動(dòng)畫階段向挖。 你可以通過啟用Profile GPU渲染和監(jiān)控動(dòng)畫階段來了解你的動(dòng)畫是否會(huì)影響應(yīng)用的性能何之。 有關(guān)更多信息溶推,請(qǐng)參閱配置文件GPU渲染演練蒜危。

類說明android.animation

These classes provide functionality for the property animation system, which allows you to animate object properties of any type.
這些類為屬性動(dòng)畫系統(tǒng)提供了功能辐赞,它允許你為任何類型的對(duì)象屬性創(chuàng)建動(dòng)畫占拍。
int, float, and hexadecimal color values are supported by default.
默認(rèn)情況下支持整形、浮點(diǎn)和十六進(jìn)制顏色值贝次。
You can animate any other type by telling the system how to calculate the values for that given type with a custom TypeEvaluator.
你可以通過告訴系統(tǒng)如何使用自定義的TypeEvaluator計(jì)算該給定類型的值來動(dòng)畫化任何其他類型蛔翅。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末山析,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子爵政,更是在濱河造成了極大的恐慌钾挟,老刑警劉巖掺出,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件汤锨,死亡現(xiàn)場(chǎng)離奇詭異荠诬,居然都是意外死亡柑贞,警方通過查閱死者的電腦和手機(jī)钧嘶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門有决,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人揽趾,你說我怎么就攤上這事苟呐∏K兀” “怎么了笆呆?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵单起,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我局冰,道長(zhǎng)康二,這世上最難降的妖魔是什么沫勿? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮蔓挖,結(jié)果婚禮上瘟判,老公的妹妹穿的比我還像新娘拷获。我一直安慰自己刀诬,他們只是感情好陕壹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著又碌,像睡著了一般铸鹰。 火紅的嫁衣襯著肌膚如雪蹋笼。 梳的紋絲不亂的頭發(fā)上剖毯,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音胶滋,去河邊找鬼究恤。 笑死丁溅,一個(gè)胖子當(dāng)著我的面吹牛窟赏,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播拷况,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼赚瘦,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了揽咕?” 一聲冷哼從身側(cè)響起亲善,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤顿肺,失蹤者是張志新(化名)和其女友劉穎挟冠,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡止潘,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了么夫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腐螟,死狀恐怖乐纸,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情庶喜,我是刑警寧澤久窟,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布入问,位于F島的核電站芬失,受9級(jí)特大地震影響棱烂,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜衬鱼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望抛蚤。 院中可真熱鬧霉颠,春花似錦、人聲如沸诉位。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽稚瘾。三九已至,卻和暖如春些椒,著一層夾襖步出監(jiān)牢的瞬間免糕,已是汗流浹背说墨。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國(guó)打工姜贡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留熄捍,地道東北人余耽。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像袱耽,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子冀续,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容