Android animation category, android category

Source: Internet
Author: User

Android animation category, android category

The Android platform provides a complete animation framework. There are two types of animations before Android.Tween Animation)AndFrame Animation ),

Corresponds to View Animation and Drawable Animation in the SDK.

After Android3.0, an animation is added.Property Animation ).

 

I. Compensation animation (res/anim/ )

Tween Animation can implement a series of conversions to the view, give two key frames, and use some algorithms to gradient the given attribute value between two key frames within the given time. You can useCodeAndXmlDefinition: AlphaAnimation...

Features:

Tween Animation can only be applied to View objects and only some attributes are supported. It does not change the attribute value, but changes the position of the View object. For example, a button is no longer in its original position after being animated, but the trigger event is still the original coordinate.

Xml must contain a heel node, which can be gradient <alpha>, scaling <scale>, moving <translate>, rotating <rotate>, or <set>. <Set> is an animation set that can contain one or more of the preceding ones.

1 <! -- Define in XML---> 2 <set android: Using interpolator = "false"> 3 <scale 4 android: interpolator = "@ android: anim/accelerate_decelerate_interpolator" 5 android: fromXScale = "1.0" 6 android: toXScale = "1.4" 7 android: fromYScale = "1.0" 8 android: toYScale = "0.6" 9 android: Export Tx = "50%" 10 android: required ty = "50%" 11 android: fillAfter = "false" 12 android: duration = "700"/> 13 </set>

Use in code:

1 ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);2 Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);3 spaceshipImage.startAnimation(hyperspaceJumpAnimation);

Define three steps for an animation. 1. Create an animation object. 2. Set the animation duration. 3. Enable the animation.

 Interpolators Interpolation

Allows an animation to move at a certain frequency to accelerate, slow down, duplicate, and rebound.

XML files are stored in:Res/anim and define android: interpolator = "@ android: anim/.." to use

Ii. Frame Animation (res/drawable /)

Frame Animation is a series of images displayed in order to simulate the Animation effect. PassAnimationDrawable.

1 <animation-list xmlns:android="http://schemas.android.com/apk/res/android"2     android:oneshot="true">3     <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />4     <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />5     <item android:drawable="@drawable/rocket_thrust3" android:duration="200" />6 </animation-list>

Must start<Animation-list>As the root element, <item> indicates the image to be rotated, And the duration Attribute indicates the display time of each item.

 1 protected void onCreate(Bundle savedInstanceState) { 2         super.onCreate(savedInstanceState); 3         setContentView(R.layout.main); 4         imageView = (ImageView) findViewById(R.id.imageView1); 5         imageView.setBackgroundResource(R.drawable.drawable_anim); 6         anim = (AnimationDrawable) imageView.getBackground(); 7     } 8  9     public boolean onTouchEvent(MotionEvent event) {10         if (event.getAction() == MotionEvent.ACTION_DOWN) {11             anim.stop();12             anim.start();13             return true;14         }15         return super.onTouchEvent(event);16     }

Note:

  • To call the setBackgroundResource method of Imageview in the Code, if you directly set the src attribute in the XML layout file, the FC
  • Stop () before the animation start (). Otherwise, the animation stops at the last frame after the first animation, so that the animation will only be triggered once.
  • The last point is mentioned in the SDK. Do not call start in onCreate, because AnimationDrawable is not completely associated with Window. If you want to start animation when the interface is displayed, you can go to onWindowFoucsChanged () start ().

3. New features added after property animation (res/animator/) // 3.0

Property Animation changes the actual attributes of the object, such as the scaling of the Button. The position and size of the Button change the attribute value. It can be applied not only to View, but also to any almost object at any time (even if there is no draws to the screen ). Property Animation only indicates a change in value within a period of time. When the value changes, you decide what to do.

Property Animation:

  • Duration: length, default length is 300 ms.
  • Time interpolation: the calculation method of attribute values, such as fast and slow.
  • Repeat count and behavior: Repeat count and behavior
  • Animator sets: an animation set that stores several animations. These animations can be played at the same time or different offsets can be set.
  • Frame refresh delay: How much time to refresh once, default is 10 MS, affected by system process scheduling and hardware

①:ValueAnimator: Includes all the core functions of the Property Animation, such as the Animation time, start and end attribute values, and the calculation method of the corresponding time attribute values.

The application ValueAnimator has two steps:

Step 1: ValuAnimiator has been completed. We only need to implement the ValueAnimator. onUpdateListener interface.

 1 ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f); 2 animation.setDuration(1000); 3 animation.addUpdateListener(new AnimatorUpdateListener() { 4     @Override 5     public void onAnimationUpdate(ValueAnimator animation) { 6        TextView tv = new TextView(getApplication()); 7               tv.setTranslationX((Float) animation.getAnimatedValue()); 8     } 9 });10 animation.setInterpolator(new CycleInterpolator(3));11 animation.start();

②:ObjectAnimator: It is a subclass of ValueAnimator. It completes the first two steps in ValueAnimator.

To makeObjectAnimatorTo update attributes correctly, we must perform the following operations:

  • The object should have a setter function: set <PropertyName> (hump name method). For example, if the attribute isfoo, You must havesetFoo()Method. If not, you can only use ValueAnimator.
  • In the preceding example, for a factory method like ofFloat, the first parameter is the object name, the second parameter is the attribute name, and the following parameter is a variable parameter. If values... If only one value is set for the parameter, it is assumed as the destination value. The change range of the attribute value is from the current value to the destination value. To obtain the current value, the object must have the getter method of the corresponding property: get <PropertyName>
  • If there is a getter method, the type of the response value should be the same as the parameter type of the corresponding setter method.
    1 copy Code 2 TV = (TextView) findViewById (R. id. textview1); 3 btn = (Button) findViewById (R. id. button1); 4 btn. setOnClickListener (new OnClickListener () {5 @ Override 6 public void onClick (View v) {7 ObjectAnimator oa 8 = ObjectAnimator. ofFloat (TV, "alpha" 9, 0f, 1f); 10 oa. setDuration (3000); 11 oa. start (); 12} 13 });

    In some cases, we may needonAnimationUpdate()Run in callbackInvalidate () method to force screen repainting.

Animation set

In an animation set, we can set the timing relationship of the animation in the group, such as simultaneous playback and sequential playback.

 1 AnimatorSet bouncer = new AnimatorSet(); 2 bouncer.play(bounceAnim).before(squashAnim1); 3 bouncer.play(squashAnim1).with(squashAnim2); 4 bouncer.play(squashAnim1).with(stretchAnim1); 5 bouncer.play(squashAnim1).with(stretchAnim2); 6 bouncer.play(bounceBackAnim).after(stretchAnim2); 7 ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f); 8 fadeAnim.setDuration(250); 9 AnimatorSet animatorSet = new AnimatorSet();10 animatorSet.play(bouncer).before(fadeAnim);11 animatorSet.start();

④: Animation monitoring

Animator. AnimatorListener defines some common interfaces of the animation.

1 onAnimationStart () 2 3 onAnimationEnd () 4 5 onAnimationRepeat () 6 7 // call when the animation is canceled and onAnimationEnd (). 8 onAnimationCancel ()

Note:

Through observation, we find that the class of AnimatorListenerAdapter implements Animator. the AnimatorListener interface {internal implementation of each method is empty}. We can inherit this class {only the method that needs to be rewritten}, rather than implementing the interface, to perform Code operations.

1 ObjectAnimator oa=ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);2 oa.setDuration(3000);3 oa.addListener(new AnimatorListenerAdapter(){4     public void on AnimationEnd(Animator animation){5         Log.i("Animation","end");6     }7 });8 oa.start();

⑤ ViewGroups transition Animation

1 <LinearLayout2 android: orientation = "vertical" 3 android: layout_width = "wrap_content" 4 android: layout_height = "match_parent" 5 android: id = "@ + id/verticalContainer" 6 <! -- Set to true. When adding or removing views, play the animation --> 7 android: animateLayoutChanges = "true"/> 8 copy the code.

Common over-animation types:

  • LayoutTransition. APPEARING: When a View appears in the ViewGroupThis ViewSet Animation
  • LayoutTransition. CHANGE_APPEARING when a View appears in the ViewGroup, this View affects other View locations.Other viewsSet Animation
  • LayoutTransition. DISAPPEARINGThis ViewSet Animation
  • LayoutTransition. CHANGE_DISAPPEARING when a View is lost in the ViewGroup, this View has an impact on other View locations.Other viewsSet Animation

⑥ View's animate () method and ViewPropertyAnimator

1 // need API12 2 imageView. animate () 3. alpha (0) 4. y (50 ). setDuration (1000) 5 // need API 12 6. withStartAction (new Runnable () {7 // the action to be performed before the animation 8 @ Override 9 public void run () {10 Log. e (TAG, "START"); 11} 12 // need API 1613 }). withenderson action (new Runnable () {14 // action to be executed after the animation 15 @ Override16 public void run () {17 Log. e (TAG, "END"); 18 runOnUiThread (new Runnable () {19 @ Override20 public void run () {21 imageView. setY (0); 22 imageView. setAlpha (1.0f); 23} 24}); 25} 26 }). start ();

The ViewPropertyAnimator class is used to animation multiple attributes of a View. This class optimizes the multi-attribute animation and merges some invalidate () to reduce the refresh View.

1/** same as the f function of the above Code */2 PropertyValuesHolder pvhX = PropertyValuesHolder. ofFloat ("alpha", 1f, 3 0f, 1f); 4 PropertyValuesHolder pvhY = PropertyValuesHolder. ofFloat ("y", 50, 0); 5 ObjectAnimator. ofPropertyValuesHolder (mBlueBall, pvhX, pvhY ). setDuration (1000 ). start ();

7. TypeEvaluator

Calculate the attribute value of the current time based on the start, end, And TimeInterpolation of the attribute.

  • IntEvaluator: the attribute value type is int.
  • FloatEvaluator: the attribute value type is float.
  • ArgbEvaluator: Property Value Type: hexadecimal color value
  • TypeEvaluator: an interface that can be used to customize the Evaluator
    1 public class FloatEvaluator implements TypeEvaluator {2 3 public Object evaluate (float fraction, Object startValue, Object endValue) {4 float startFloat = (Number) startValue ). floatValue (); 5/** 6 fraction is calculated from 0 ~ Factor 7 */8 return startFloat + fraction * (Number) endValue). floatValue ()-startFloat); 9} 10}

     

 Use property animation in velocity XML

XML:

1 <?xml version="1.0" encoding="utf-8"?>  2 <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"  3     android:duration="1000"  4     android:propertyName="scaleX"  5     android:valueFrom="1.0"  6     android:valueTo="2.0"  7     android:valueType="floatType" >  8 </objectAnimator>

Code:

1 public void scaleX (View view) 2 {3 // load animation 4 Animator anim = AnimatorInflater. loadAnimator (this, R. animator. scalex); 5 anim. setTarget (mMv); 6 anim. start (); 7}

Thank you for your learning!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.