Property Animation Overview 屬性動畫總覽
The property animation system is a robust framework that allows you to animate almost anything.
屬性動畫系統是一個健壯的框架,它允許你為任何東西創建動畫。
You can define an animation to change any object property over time, regardless of whether it draws to the screen or not.
你可以定義一個隨時間改變任何對象屬性的動畫,無論他是否繪制在屏幕上。
A property animation changes a property's (a field in an object) value over a specified length of time.
屬性動畫會在指定的時間長度內更改屬性的(對象中的字段)值。
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.
為某個東西創建動畫,你需要指定你想要創建動畫的這個對象的屬性,例如一個對象在屏幕上的位置,你想要為它動畫多久,和你想要在什么值之間動畫。
The property animation system lets you define the following characteristics of an animation:
屬性動畫系統允許你定義動畫以下的這些的特性:
- Duration: You can specify the duration of an animation. The default length is 300 ms.
- 持續時間:你可以指定動畫的持續時間。默認的長度是300ms
- Time interpolation: You can specify how the values for the property are calculated as a function of the animation's current elapsed time.
- 時間插值:您可以指定屬性的值如何作為動畫當前流逝時間的函數進行計算的。
- 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.
- 重復計數和行為:當動畫到達持續時間的終端時,你可以定義動畫是否重復和重復次數。你還可以指定是否想要動畫反向播放。設置為反向播放動畫向前,然后向后重復,直到達到重復的數量。設置它反向向前播放這個動畫,然后向后重復,直到重復次數到達為止。
- Animator sets: You can group animations into logical sets that play together or sequentially or after specified delays.
- 動畫集:你可以將動畫分組為邏輯集合,它們在一起或按順序或在指定的延遲之后播放。
- 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.
- 幀刷新延遲:你可以指定刷新動畫幀的頻率。默認設置為每10毫秒刷新一次,但應用程序可以刷新幀的速度最終取決于整個系統的繁忙程度以及系統能為底層定時器服務的速度。
How Property Animation Works 屬性動畫是如何工作的
First, let's go over how an animation works with a simple example.
首先,讓我們通過一個簡單的示例走一遍動畫是如何工作的。
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描述了一個假想對象,其對象是x屬性,表示它在屏幕上的水平位置。動畫的持續時間設置為40毫秒,移動距離為40像素。
Every 10 ms, which is the default frame refresh rate, the object moves horizontally by 10 pixels.
每10ms,這是默認的幀刷新率,這個對象水平移動10像素。這個40ms的終點。
At the end of 40ms, the animation stops, and the object ends at horizontal position 40.
在40ms,動畫停止,同時這個對象停止在水平位置40的地方。
This is an example of an animation with linear interpolation, meaning the object moves at a constant speed.
這是一個具有水平線性插值的動畫示例,意味著這個對象以恒定的速度移動。
You can also specify animations to have a non-linear interpolation.
你也可以指定具有非線性插值的動畫。
Figure 2 illustrates a hypothetical object that accelerates at the beginning of the animation, and decelerates at the end of the animation.
圖2說明了一個假設的對象,在動畫開始時加速,然后在動畫結束時減速。
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.
這個對象仍然在40ms移動40像素,但是是非線性的。一開始,這個動畫加速直到中間點。然后,從中間點減速直到動畫結束。
As Figure 2 shows, the distance traveled at the beginning and end of the animation is less than in the middle.
如圖2所示,動畫開始和結束的一段時間內所走的距離小于中間一段時間的距離。
Let's take a detailed look at how the important components of the property animation system would calculate animations like the ones illustrated above.
讓我們詳細看看屬性動畫系統的重要組件如何計算上面提到的動畫。
Figure 3 depicts how the main classes work with one another.
圖3描述了主要的類是如何彼此工作的。
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對象保持追蹤你的動畫的時間,例如:這個動畫已經運行了多久,和它正在動畫的屬性當前的值。
The ValueAnimator encapsulates a TimeInterpolator, which defines animation interpolation, and a TypeEvaluator, which defines how to calculate values for the property being animated.
ValueAnimator封裝了一個TimeInterpolator,它定義了動畫插值,和一個TypeEvaluator,它定義了如何計算將被動畫的屬性的值。
For example, in Figure 2, the TimeInterpolator used would be AccelerateDecelerateInterpolator and the TypeEvaluator would be IntEvaluator.
例如,在圖2中,使用的時間插值器將會是AccelerateDecelerateInterpolator,和類型計算器就將會是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.
為了開啟一個動畫,創建一個ValueAnimator和賦予它的屬性你想要的動畫的開始和結束的值,以及動畫的持續時間。
When you call start() the animation begins.
當你調用start()方法,動畫開啟。
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.
在整個動畫中,ValueAnimator計算在0和1之間的過去的分數,基于動畫的持續時間和經過了多少時間。
The elapsed fraction represents the percentage of time that the animation has completed, 0 meaning 0% and 1 meaning 100%.
這個過去的分數表現了動畫完成的時間百分比,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中,過去的分數在t=10ms時將會是0.25,因為總共持續時間的時為t=40ms。
When the ValueAnimator is done calculating an elapsed fraction, it calls the TimeInterpolator that is currently set, to calculate an interpolated fraction.
當ValueAnimator完成計算過去的分數時,它將會調用當前設置的TimeInterpolator,去計算插值分數。
An interpolated fraction maps the elapsed fraction to a new fraction that takes into account the time interpolation that is set.
內插分數將流逝分數映射到考慮了設置的時間內插的新分數。
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中,由于動畫緩慢加速,因此在t = 10 ms時,插值分數約為0.15,小于流逝分數.25。 在圖1中,內插分數總是與流逝分數相同。
例如,在圖2中,由于動畫緩慢加速,在t=10ms時刻,插值分數約為0.15,小于流逝分數0.25。
In Figure 1, the interpolated fraction is always the same as the elapsed fraction.
在圖1中,插值分數總是和消逝分數相等。
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.
當插值分數被計算出來,ValueAnimator根據插值分數、動畫開始和結束的值,調用合適的TypeEvaluator去計算你正在動畫的屬性的值。
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時,插值分數是0.15,所以此時屬性將會是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示例項目中的com.example.android.apis.animation包提供了許多有關如何使用屬性動畫系統的示例。
How Property Animation Differs from View Animation 屬性動畫與View動畫的差別
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動畫系統提供了僅對View對象進行動畫處理的功能。因此如果你想為非View對象設置動畫效果,你不得不實現自己的代碼來執行操作。
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動畫也受限于這樣一個事實,它僅暴露了View對象的一些方面,例如縮放和旋轉一個View,但是不包括背景顏色。
Another disadvantage of the view animation system is that it only modified where the View was drawn, and not the actual View itself.
視圖動畫系統的另一個缺點是只能在視圖被繪制的地方進行修改,而不是實際的視圖本身。
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.
例如,如果你使按鈕動畫的穿過屏幕,按鈕被正確的繪制,但是事實上你點擊按鈕的位置卻沒有改變,所以你必須實現自己的邏輯來處理這個問題。
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.
使用屬性動畫系統,這些約束被完全刪除,并且可以為任何對象(視圖和非視圖)的任何屬性設置動畫,并且對象本身實際上被修改。
The property animation system is also more robust in the way it carries out animation.
動畫屬性系統在執行動畫時也更加強壯。
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.
從較高層次上講,你可以分配動畫到你想要動畫的屬性上,例如顏色、位置、或大小和可以定義動畫的方面如:插值器和多個同步動畫。
The view animation system, however, takes less time to setup and requires less code to write.
然而,View動畫系統,花費更少的時間去設置和需要寫更少的代碼。
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.
如果動畫完成了你需要執行的所有事,或者你已有的代碼已經按照你想要的方式運行,則無需使用屬性動畫系統。
It also might make sense to use both animation systems for different situations if the use case arises.
如果出現用例,那么在不同情況下使用這兩種動畫系統也是有意義的。
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中找到大部分屬性動畫系統的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動畫系統在android.view.animation中已經定義了許多插值器,同樣你也可以在屬性動畫中使用這些插值器。
The following tables describe the main components of the property animation system.
接下來的這些介紹了屬性動畫系統的主要的組件。
The Animator class provides the basic structure for creating animations.
Animator類提供了創建動畫的基礎結構。
You normally do not use this class directly as it only provides minimal functionality that must be extended to fully support animating values.
你通常不直接使用此類,因為它只提供最小的功能,必須擴展才能完全支持動畫值。
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告訴屬性動畫系統如何為給定的屬性計算值。
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類提供的時間數據,動畫開始和終止的值,然后基于這些數據計算這個屬性的動畫值。
The property animation system provides the following evaluators:
動畫屬性系統提供一下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.一個插值器,其變化開始后向前閃爍。 |
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.內插器的變化在最后反彈。 |
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.
時間插值器定義動畫中的特定值如何作為時間的函數進行計算。
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.
舉個例子,你可以指定動畫在整個動畫中線性發生,意味著動畫整個時間內平均的移動,
或者你可以指定動畫使用非線性時間,例如,在動畫開始時加速和結束時減速。
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.
如果提供的插值器沒有一個適合你使用,創建一個你自己的實現了TimeInterpolator接口插值器。
See Using interpolators for more information on how to write a custom interpolator.
查看使用插值器獲取更多關于如何寫一個自定義插值器的信息。(有關如何編寫自定義插補器的更多信息,請參見使用插補器。 備注的是谷歌翻譯的,谷歌翻譯就是牛逼)。
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.一個插值器,其變化開始后向前閃爍。 |
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.內插器的變化在最后反彈。 |
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進行動畫制作
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值,浮點值或顏色值來設置動畫效果,ValueAnimator類可以為動畫的持續時間設置某種類型的值的動畫。
You obtain a ValueAnimator by calling one of its factory methods: ofInt(), ofFloat(), or ofObject(). For example:
通過調用它的任一工廠方法:onInt()、ofFloat()、或者ofObject(),你可以獲取一個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.
在這份代碼中,當start()方法運行時,ValueAnimator開始計算在0與100之間,持續時間為1000ms的動畫的值。
You can also specify a custom type to animate by doing the following:
當然你也可以通過執行以下操作,指定一個自定義的類型來創建動畫效果:
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以及持續時間1000ms的條件下計算這個動畫的值。
You can use the values of the animation by adding an AnimatorUpdateListener to the ValueAnimator object, as shown in the following code:
你可以使用這個動畫的值通過給ValueAnimator來添加一個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()方法中,你可以訪問更新后的動畫值,并將其用于其中一個視圖的屬性中。
Animating with ObjectAnimator 使用ObjectAnimator創建動畫
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的一個子類(在上一節中討論過),它將ValueAnimator的時序引擎和值計算與對目標對象的命名屬性進行動畫處理的功能相結合。
This makes animating any object much easier, as you no longer need to implement the ValueAnimator.AnimatorUpdateListener, because the animated property updates automatically.
這使得任何對象的動畫更容易,因為你不再需要實現ValueAnimator.AnimatorUpdateListener,因為動畫屬性會自動更新。
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:
實例化一個ObjectAnimator類似于一個ValueAnimator,但是你還需要指定該對象的屬性名稱(作為字符串)以及值之間進行動畫處理:
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屬性,你必須執行以下操作:
- 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.
你正在設置動畫的對象屬性必須以set()的形式具有setter函數(駱駝大小寫)。 由于ObjectAnimator在動畫期間自動更新屬性,因此必須能夠使用此setter方法訪問屬性。 例如,如果屬性名稱是foo,則需要有一個setFoo()方法。
If this setter method does not exist, you have three options:
如果setter方法不存在,你擁有以下三個選擇:- Add the setter method to the class if you have the rights to do so.在這個類中添加setter方法,如果你有權限這樣做。
- 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.使用你有權修改的包裝類,并讓該包裝接收有效的setter方法的值并將其轉發給原始對象。
- 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.如果你在其中一個ObjectAnimator工廠方法中為values ...參數指定了僅一個值,則它被假定為動畫的結束值。 因此,你正在動畫的對象屬性必須具有用于獲取動畫起始值的getter函數。 getter函數必須采用get <PropertyName>()的形式。 例如,如果屬性名稱是foo,則需要有一個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:你要動畫的屬性的getter(如果需要)和setter方法必須以與指定給ObjectAnimator的開始和結束值相同的類型進行操作。 例如,如果構造以下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.根據你要動畫的屬性或對象,你可能需要在視圖上調用invalidate()方法以強制屏幕使用更新的動畫值重繪本身。 你可以在onAnimationUpdate()回調中執行此操作。 例如,對Drawable對象的顏色屬性進行動畫處理只會導致該對象重繪時自動更新屏幕。View所有的屬性設置器,例如setAlpha()和setTranslationX()都會正確的廢止View,因此當調用這些方法時,你不需要使View無效。有關偵聽器的更多信息,請參閱關于動畫偵聽器的部分。
Choreographing Multiple Animations with AnimatorSet 用AnimatorSet編排多個動畫
In many cases, you want to play an animation that depends on when another animation starts or finishes.
在許多情況下,你想播放取決于另外一個動畫的開始或結束的動畫。
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系統讓你將動畫捆綁到一個AnimatorSet中,以便你指定動畫立刻、按照順序、或者在一個特定的延遲開始播放。你也可以將AnimatorSet對象嵌套在對方內。
The following sample code taken from the Bouncing Balls sample (modified for simplicity) plays the following Animator objects in the following manner:
接下來摘自Bouncing Balls示例(簡單修改)的示例代碼按以下方式播放以下Animator對象:
- Plays bounceAnim.
- Plays squashAnim1, squashAnim2, stretchAnim1, and stretchAnim2 at the same time.
- Plays bounceBackAnim.
- 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.
關于如何使用animator集合更完整的示例,請查看在APIDemos中的Bouncing Balls示例。
Animation Listeners 動畫偵聽者
You can listen for important events during an animation's duration with the listeners described below.
在動畫持續時間內,你可以偵聽以下描述的偵聽器中的重要事件。
- 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.
- 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.
Animating Layout Changes to ViewGroups 動畫布局更改為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.
屬性動畫系統提供了對ViewGroup對象進行動畫變化的功能,并提供了一種簡單的方法來為View對象本身制作動畫。
You can animate layout changes within a ViewGroup with the LayoutTransition class.
你可以使用LayoutTransition類對ViewGroup中的布局更改進行動畫處理。
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中刪除它們時,或者當你使用VISIBLE,INVISIBLE或GONE調用View的setVisibility()方法時,經過出現和消失的動畫。
The remaining Views in the ViewGroup can also animate into their new positions when you add or remove Views.
當添加或刪除視圖時,ViewGroup中的其余視圖也可以動畫到他們的新位置。
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:
你可以通過調用setAnimator()并使用下列LayoutTransition常量之一傳入Animator對象來在LayoutTransition對象中定義以下動畫:
- 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.
你可以為這四種類型的事件定義自己的自定義動畫,以自定義布局轉換的外觀,或者僅告訴動畫系統使用默認動畫。
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示例向你展示了如何為布局轉換定義動畫,然后在你想要制作動畫的視圖對象上設置動畫。
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及其相應的layout_animations_by_default.xml布局資源文件顯示如何為XML中的ViewGroups啟用默認布局轉換。 唯一需要做的就是將ViewGroup的android:animateLayoutchanges屬性設置為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.
將此屬性設置為true會自動生成從ViewGroup添加或刪除的視圖以及ViewGroup中剩余的視圖。
Using StateListAnimator to animate view state changes 使用StateListAnimator創建視圖狀態變更動畫
The StateListAnimator class lets you define animators that run when the state of a view changes.
StateListAnimator類允許你定義在View的狀態變化時運行的動畫。
This object behaves as a wrapper for an Animator object, calling that animation whenever the specified view state (such as "pressed" or "focused") changes.
該對象充當動畫對象的包裝器,每當指定的視圖狀態(如“按下”或“焦點”)更改時調用該動畫。
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資源中定義,每個子元素指定由StateListAnimator類定義的不同視圖狀態。
Each <item> contains the definition for a property animation set.
每一個<item>包含這個屬性動畫集合的定義。
For example, the following file creates a state list animator that changes the x and y scale of the view when it's pressed:
舉個栗子,下面的文件創建了一個狀態列表動畫器,用于當視圖被按壓時改變它的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:
要將狀態列表動畫添加到視圖,請按如下所示添加android:stateListAnimator屬性:
<Button android:stateListAnimator="@xml/animate_scale"
... />
Now the animations defined in animate_scale.xml are used when this button's state changes.
當這個按鈕的狀態改變,當前定義在animate_scale.xml動畫被使用。
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.
或者改為將狀態列表動畫器分配給代碼中的視圖,請使用AnimatorInflater.loadStateListAnimator()方法,并使用View.setStateListAnimator()方法將動畫器分配給視圖。
Or instead of animating properties of the view, you can play a drawable animation between state changes, using AnimatedStateListDrawable.
或者,你可以使用AnimatedStateListDrawable在狀態更改之間播放可繪制動畫,而不是動畫視圖的屬性。
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中的一些系統小部件默認使用這些動畫。 以下示例顯示如何將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.
如果你為一個Android系統不知道的類型創建動畫,你可以通過實現TypeEvaluator接口創建你自己的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系統所熟知的類型是int,float或color,它們通過IntEvaluator,FloatEvaluator和ArgbEvaluator類型Evaluator。
There is only one method to implement in the TypeEvaluator interface, the evaluate() method.
在TypeEvaluator接口中只有一個方法需要執行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.
這允許你正在使用的動畫在動畫當前點為你的動畫屬性返回適當的值。
The FloatEvaluator class demonstrates how to do this:
FloatEvaluator類演示了如何執行此操作:
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.
注意:當ValueAnimator(或ObjectAnimator)運行時,它會計算動畫當前流逝的部分(介于0和1之間的一個值),然后根據你使用的插值器計算插值版本。內插分數是TypeEvaluator通過分數參數接收的值,因此計算動畫值時不必考慮插值器。
Using Interpolators 使用插值器
An interpolator define how specific values in an animation are calculated as a function of time.
插值器定義了在動畫中特定值是如何作為時間的函數進行計算的。
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.
舉個例子,你可以指定動畫在整個動畫中線性發生,意味著動畫整個時間內平均的移動,或者你可以指定動畫使用非線性時間,例如,在動畫開始時加速和結束時減速。
Interpolators in the animation system receive a fraction from Animators that represent the elapsed time of the animation.
動畫系統中的插值器會接收來自動畫器的分數,表示動畫已用時間。
Interpolators modify this fraction to coincide with the type of animation that it aims to provide.
插值器修改此分數以符合它旨在提供的動畫類型。
The Android system provides a set of common interpolators in the android.view.animation package.
Android系統在android.view.animation包中提供一組常用的插值算法。
If none of these suit your needs, you can implement the TimeInterpolator interface and create your own.
如果這些都不符合你的需求,你可以實現TimeInterpolator接口并創建你自己的。
As an example, how the default interpolator AccelerateDecelerateInterpolator and the LinearInterpolator calculate interpolated fractions are compared below.
例如,下面比較默認插值器AccelerateDecelerateInterpolator和LinearInterpolator計算插值分數的方式。
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對經過的分數沒有影響。 AccelerateDecelerateInterpolator加速進入動畫并減速。 以下方法定義了這些內插器的邏輯:
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:
下表表示這些插補器對持續1000毫秒的動畫計算的近似值:
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 指定關鍵幀
A Keyframe object consists of a time/value pair that lets you define a specific state at a specific time of an animation.
一個Keyframe對象由一個時間/值對組成,它允許你在動畫的特定時間定義特定的狀態。
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.
每個關鍵幀還可以有自己的插補器,以控制前一個關鍵幀時間與該關鍵幀時間之間的間隔內的動畫行為。
To instantiate a Keyframe object, you must use one of the factory methods, ofInt(), ofFloat(), or ofObject() to obtain the appropriate type of Keyframe.
要實例化一個Keyframe對象,必須使用工廠方法之一的Int(),ofFloat()或ofObject()來獲取適當類型的Keyframe。
You then call the ofKeyframe() factory method to obtain a PropertyValuesHolder object.
然后調用ofKeyframe()工廠方法來獲取PropertyValuesHolder對象。
Once you have the object, you can obtain an animator by passing in the PropertyValuesHolder object and the object to animate.
獲得對象后,可以通過傳遞PropertyValuesHolder對象和對象來獲取動畫。
The following code snippet demonstrates how to do this:
以下代碼片段演示了如何執行此操作:
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.
屬性動畫系統允許View對象的簡化動畫,并且與視圖動畫系統相比具有一些優點。
The view animation system transformed View objects by changing the way that they were drawn.
視圖動畫系統通過改變它們被繪制的方式來轉換視圖對象。
This was handled in the container of each View, because the View itself had no properties to manipulate.
這是在每個視圖的容器中處理的,因為視圖本身沒有可操作的屬性。
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.
這導致視圖被動畫,但在視圖對象本身中沒有改變。 這導致行為,例如對象仍然存在于其原始位置,即使它是在屏幕上的不同位置繪制的。
In Android 3.0, new properties and the corresponding getter and setter methods were added to eliminate this drawback.
在Android 3.0中,添加了新的屬性和相應的getter和setter方法來消除這個缺點。
The property animation system can animate Views on the screen by changing the actual properties in the View objects.
屬性動畫系統可以通過改變視圖對象中的實際屬性來在屏幕上動畫視圖。
In addition, Views also automatically call the invalidate() method to refresh the screen whenever its properties are changed.
另外,視圖也會自動調用invalidate()方法刷新屏幕,只要其屬性發生更改。
The new properties in the View class that facilitate property animations are:
有助于屬性動畫的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對象的屬性(例如其顏色或旋轉值)設置動畫效果,你只需創建屬性動畫器并指定要設置動畫效果的View屬性即可。舉個栗子:
ObjectAnimator.ofFloat(myView, "rotation", 0f, 360f);
For more information on creating animators, see the sections on animating with ValueAnimator and ObjectAnimator.
有關創建動畫的更多信息,請參閱關于使用ValueAnimator和ObjectAnimator進行動畫制作的章節。
Animating with ViewPropertyAnimator 通過ViewPropertyAnimator創建動畫
The ViewPropertyAnimator provides a simple way to animate several properties of a View in parallel, using a single underlying Animator object.
ViewPropertyAnimator提供了一種簡單的方法,可以使用單個基礎Animator對象并行地對View的幾個屬性進行動畫處理。
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非常相似,因為它修改了視圖屬性的實際值,但在同時動畫多個屬性時效率更高。
In addition, the code for using the ViewPropertyAnimator is much more concise and easier to read.
此外,使用ViewPropertyAnimator的代碼更加簡潔易讀。
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.
以下代碼片段顯示了在同時為視圖的x和y屬性設置動畫時,使用多個ObjectAnimator對象,單個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中聲明動畫
The property animation system lets you declare property animations with XML instead of doing it programmatically.
屬性動畫系統允許你用XML聲明屬性動畫,而不是以編程方式進行。
By defining your animations in XML, you can easily reuse your animations in multiple activities and more easily edit the animation sequence.
通過用XML定義動畫,你可以輕松地在多個活動中重復使用動畫,并更輕松地編輯動畫序列。
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.
為了將使用新屬性動畫API的動畫文件與使用舊視圖動畫框架的動畫文件區分開來,從Android 3.1開始,應該將屬性動畫的XML文件保存在res/animator/目錄中。
The following property animation classes have XML declaration support with the following XML tags:
以下屬性動畫類使用以下XML標記支持XML聲明:
- ValueAnimator - <animator>
- ObjectAnimator - <objectAnimator>
- AnimatorSet - <set>
To find the attributes that you can use in your XML declaration, see Animation Resources.
為了找到你可以在XML中使用的屬性,請查看Animation Resources。
The following example plays the two sets of object animations sequentially, with the first nested set playing two object animations together:
接下來的例子順序的播放了兩個對象動畫組合,第一個嵌套集合一起播放兩個對象動畫:
<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.
為了運行此動畫,你必須將代碼中的XML資源充入AnimatorSet對象,然后在開始動畫設置之前為所有動畫設置目標對象。
Calling setTarget() sets a single target object for all children of the AnimatorSet as a convenience. The following code shows how to do this:
為方便起見,調用setTarget()為AnimatorSet的所有子節點設置一個目標對象。 以下代碼顯示了如何執行此操作:
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,你必須膨脹對象,添加AnimatorUpdateListener,獲取更新后的動畫值,并將其用于你的某個視圖的屬性中,如以下代碼所示:
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 .
有關定義屬性動畫的XML語法的信息,請參閱動畫資源。
Implications for UI performance 對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的動畫器會為動畫運行的每個幀導致額外的渲染工作。 因此,使用資源密集型動畫可能會對應用程序的性能產生負面影響。
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的動畫添加到渲染管道的動畫階段。 你可以通過啟用Profile GPU渲染和監控動畫階段來了解你的動畫是否會影響應用的性能。 有關更多信息,請參閱配置文件GPU渲染演練。
類說明android.animation
These classes provide functionality for the property animation system, which allows you to animate object properties of any type.
這些類為屬性動畫系統提供了功能,它允許你為任何類型的對象屬性創建動畫。
int, float, and hexadecimal color values are supported by default.
默認情況下支持整形、浮點和十六進制顏色值。
You can animate any other type by telling the system how to calculate the values for that given type with a custom TypeEvaluator.
你可以通過告訴系統如何使用自定義的TypeEvaluator計算該給定類型的值來動畫化任何其他類型。