Android Animation Study Notes

Source: Internet
Author: User
Tags element groups time in milliseconds xml example

Android Animation Study Notes

For the implementation of Animation, Android provides Animation and introduces two Animation modes in Android SDK:

1. Tween Animation: A gradient Animation is generated by constantly performing image transformations (translation, scaling, and rotation) on objects in the scenario;

2. Frame Animation: it is an Animation for converting images that are prepared in sequence.

Animation type

Next, let's take a look at the animation types provided by Android. Android animation consists of four types

In the XML file:

  • Alpha gradient transparency animation effect
  • Scale scaling Animation
  • Animated effect of moving the translate position
  • Rotate screen transfer rotation animation effect

    The corresponding classes are defined in the Java source code. You can use these class methods to obtain and operate the corresponding attributes:

    • AlphaAnimation gradient transparency animation effect
    • ScaleAnimation gradient scaling animation effect
    • TranslateAnimation
    • RotateAnimation image transfer rotation animation effect

      Tween Animation

      A tween animation performs a series of simple conversions (location, size, rotation, transparency) on the content of the view object ). If you have a text view object, you can move it, rotate it, and make it larger or smaller. If there is a background image under the text, the background image will also be converted with the file.

      Use XML to define Tween Animation

      The XML file of the animation is in the project.Res/animDirectory. This file must contain a root element Interpolation element or adding all the above elements In element groups, by default, all animation commands occur simultaneously. To enable them to occur in sequence, you need to set a special attribute startOffset. Animation commands define what kind of conversions you want to perform. when they happen, how long should they be executed? The conversions can be continuous or at the same time. For example, if you want to move the text content from the left to the right, then rotate the text 180 degrees, or rotate the text content simultaneously during the movement, no conversion requires some special parameters (the size of the start and end sizes, the rotation angle of the start and end, and so on). You can also set some basic parameters (for example, if several conversions occur simultaneously, you can set the same Start Time for them. If the conversion is based on the sequence, the calculation Start Time plus the cycle.

      Common node attributes of Tween Animation

      Attribute [type] Function Remarks
      Duration [long] Attribute is animation duration Time in milliseconds
      FillAfter [boolean] If it is set to true, the animation will be applied after the animation ends.
      FillBefore [boolean] If this parameter is set to true, the animation is applied before the animation starts.

      Interpolator

      Specifies an animation insertor. There are some common plug-ins
      Accelerate_decelerate_interpolator
      Accelerator-slowdown animation inserter
      Accelerate_interpolator
      Acceleration-animation insertor
      Decelerate_interpolator
      Slowdown-animation inserter
      Other animation Effects
      RepeatCount [int] Number of animation repetitions
      RepeatMode [int] Define repeated Behaviors 1: Start again 2: plays backward
      StartOffset [long] The time interval between the animation, starting from the time when the animation was stopped
      ZAdjustment [int] Changing the Z Order of an animation 0: Keep Z Order unchanged
      1: Keep at the top
      -1: Keep at the bottom layer

      Table 2

      XML Node Function Description
      Alpha Gradient transparency animation effect
      Android: fromAlpha = "0.1 ″
      Android: toAlpha = "1.0 ″
      Android: duration = "3000"/>
      FromAlpha

      Transparency when attribute is animation start

      0.0 indicates completely transparent
      1.0 indicates completely opaque
      The above value is a float data type number between 0.0 and 1.0.

      Duration is the animation duration, in ms.

      ToAlpha

      The property is the transparency when the animation ends.

      Table 3

      Scale Gradient scaling animation effect
      Android: interpolator = "@ android: anim/accelerate_decelerate_interpolator"
      Android: fromXScale = "0.0 ″
      Android: toXScale = "1.4 ″
      Android: fromYScale = "0.0 ″
      Android: toYScale = "1.4 ″
      Android: Required Tx = "50%"
      Android: Required ty = "50%"
      Android: fillAfter = "false"
      Android: startOffset = "700"
      Android: duration = "700 ″
      Android: repeatCount = "10"/>
      FromXScale [float] fromYScale [float] It is the scaling size on the X and Y coordinates when the animation starts. 0.0 indicates shrinking to none
      1.0 indicates normal scaling-free
      A value smaller than 1.0 indicates contraction.
      Value greater than 1.0 indicates Amplification
      ToXScale [float]
      ToYScale [float]
      It is the scaling size on the X and Y coordinates when the animation ends.
      PivotX [float]
      Ty [float]
      It is the starting position of the animation relative to the X and Y coordinates of the object. Attribute value description: from 0%-100%, 50% is the midpoint position on the X or Y coordinate of the object.

      Table 4

      Translate Animation Effect
      Android: fromXDelta = "30 ″
      Android: toXDelta = "-80 ″
      Android: fromYDelta = "30 ″
      Android: toYDelta = "300 ″
      Android: duration = "2000"/>
      FromXDelta
      ToXDelta
      It is the position on the X coordinate at the animation end and start.
      FromYDelta
      ToYDelta
      It is the position on the Y coordinate of the animation and the start point of the animation.

      Table 5

      Rotate Animation effects of screen transfer and Rotation
      Android: interpolator = "@ android: anim/accelerate_decelerate_interpolator"
      Android: fromDegrees = "0 ″
      Android: toDegrees = "+ 350 ″
      Android: Required Tx = "50%"
      Android: Required ty = "50%"
      Android: duration = "3000"/>
      FromDegrees It is the angle of the object when the animation starts. Description
      If the angle is negative, it indicates clockwise rotation.
      If the angle is positive, it indicates clockwise rotation.
      (Negative from -- to positive: clockwise rotation)
      (Negative from -- to negative: counter-clockwise rotation)
      (Positive from -- to positive: clockwise rotation)
      (Positive from -- to negative: clockwise rotation)
      ToDegrees The Rotation Angle of an object can be greater than 360 degrees when the animation ends.
      PivotX
      Ty
      It is the starting position of the animation relative to the X and Y coordinates of the object. Note: The preceding two attribute values are from 0% to 100%.
      50% indicates the point position on the X or Y coordinate of the object.

      The following is a complete XML definition (provided by the SDK)

              
               
                  
                   
                
            
           

      How to Use Tween Animation

      Use the static method loadAnimation () of the AnimationUtils class to load the animated XML file in XML.

      // Main. in xml, ImageViewImageView spaceshipImage = (ImageView) findViewById (R. id. spaceshipImage); // load the Animation hyperspaceJumpAnimation = AnimationUtils. loadAnimation (this, R. anim. hyperspace_jump); // use ImageView to display the animated spaceshipImage. startAnimation (hyperspaceJumpAnimation );

      How to define animations in Java code

      // Define the Animation Instance Object private Animation myAnimation_Alpha; private Animation myAnimation_Scale; private Animation myAnimation_Translate; private Animation myAnimation_Rotate in the Code; // Initialize an instance object myAnimation_Alpha = new AlphaAnimation (0.1f, 1.0f) according to their respective constructor; myAnimation_Scale = new ScaleAnimation (0.0f, 1.4f, 0.0f, 1.4f, Animation. RELATIVE_TO_SELF, 0.5f, Animation. updated, 0.5f); myAnimation_Translate = new TranslateAnimation (30366f,-80366f, 30366f, 300366f); myAnimation_Rotate = new RotateAnimation (0.0f, + 350366f, Animation. RELATIVE_TO_SELF, 0.5f, Animation. RELATIVE_TO_SELF, 0.5f );

      Explanation of interpolator

      Interpolator defines the rate of change of an animation ). This allows the basic animation effects (alpha, scale, translate, and rotate) to accelerate, slow down, and repeat.

      Interpolator defines the speed at which an animation changes, including constant speed, positive acceleration, negative acceleration, and irregular acceleration. Interpolator is a base class that encapsulates all the common methods of Interpolator. It has only one method, that is, getInterpolation (float input ), this method maps a point on the timeline to a multiplier to be applied to the transformations of an animation. Android provides several Interpolator subclasses to achieve different speed curves, as shown below:

      AccelerateDecelerateInterpolator The speed changes are slow at the beginning of the animation and in the middle of the introduction.
      AccelerateInterpolator Speed changes are slow at the beginning of the animation and acceleration starts.
      CycleInterpolator Specifies the number of times the animation is played cyclically, and the speed changes along the sine curve.
      DecelerateInterpolator The speed changes slowly at the beginning of the animation, and then starts to slow down.
      LinearInterpolator Changes at an even rate in an animation

      Frame Animation

      Frame Animation is an image prepared in advance for sequential playback, similar to a movie. Unlike the animation package, the Android SDK provides another class, AnimationDrawable, to define and use Frame Animation.

      Frame Animation can be defined in XML Resource (or stored inRes \ animFolder), you can also useAPI definition in AnimationDrawable. Since Tween Animation and Frame Animation are very different, the XML definition format is also completely different. The format is:The first is the animation-list root node. The animation-list root node contains multiple item subnodes. Each item node defines an animation, the drawable resource of the current frame and the duration of the current frame.The following describes the elements of a node:

      XML attributes Description
      Drawable Drawable resource referenced by the current frame
      Duration Display Time of the current frame (in milliseconds)
      Oneshot If it is true, the animation is played only once and stops at the last frame. If it is set to false, the animation is played cyclically.
      VariablePadding If true, allows the drawable's padding to change based on the current state that is selected.
      Visible Specifies the initial visibility of drawable. The default value is flase;

      The following is a specific XML example to define a frame-by-frame animation:

          
               
               
           

      The XML above defines a Frame Animation, which contains three animations. Three animations apply three pictures in drawable: rocket_thrust1, rocket_thrust2, and rocket_thrust3, each animation lasts for 200 milliseconds.

      Then we save the above XML inRes/anim/TextNamed rocket_thrust.xml in the folder to display the animation code:

      AnimationDrawable rocketAnimation;public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);  rocketImage.setBackgroundResource(R.anim.rocket_thrust);  rocketAnimation = (AnimationDrawable) rocketImage.getBackground();}public boolean onTouchEvent(MotionEvent event) {  if (event.getAction() == MotionEvent.ACTION_DOWN) {    rocketAnimation.start();    return true;  }  return super.onTouchEvent(event);}

      Result of code execution: three images are played in sequence.

      One thing to note is that the Code for starting the Frame Animation is rocketAnimation. start (); cannot be in OnCreate (), because in OnCreate (), AnimationDrawable is not completely bound to ImageView, And the animation is started in OnCreate, you can only see the first image. This is actually implemented in the drag event.

      Next, let's take a look at the introduction to AnimationDrawable In the Android SDK:

      AnimationDrawable

      Get and set animation attributes
      Int getDuration () Obtain the animation duration
      Int getNumberOfFrames () Get the number of animation Frames
      Boolean isOneShot ()

      Void setOneShot (boolean oneshot)

      Get oneshot attributes
      Set the oneshot attribute
      Void inflate (Resurce r, XmlPullParser p,
      AttributeSet attrs)
      Add and retrieve frame animations
      Drawable getFrame (int index) Obtain the Drawable resource of a frame.
      Void addFrame (Drawable frame, int duration) Add frames for the current animation (resource, duration)
      Animation Control
      Void start () Start Animation
      Void run () You cannot directly drop the call. Use start () instead.
      Boolean isRunning () Whether the current animation is running
      Void stop () Stop current Animation

      Reference: Android SDK

      Moandroid.com

      Eoeandroid.com

      161 you also like the following: android Service learning notes Android Activity and Intent mechanism learning notes Android Nine Patch pictures and button background Android style and theme Android process and thread Android Face Detection class FaceDetectZ tips? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcgo8aW1nIGNsYXNzPQ =" wumii-image "src =" http://www.2cto.com/uploadfile/Collfiles/20150305/2015030510170673.png "alt =" \ "> Android processes are not associated with threads [?] Category: Android green channel: Follow my favorites to contact me with feisky
      Follow-10
      Fans-673 + followed by 140 (Please rate your article )? Previous Article: how to calculate the running time of the matlab program
      ? Next article: Study Notes on Android Network Connection Processing
      Feedback #1 floor by the legendary Xiang Ge would like to ask the landlord, if an instance loads multiple animations, how to implement it using code?
      For example:
      You can use xml to implement gradient and screen position conversion as follows:

      Xmlns: android = "http://schemas.android.com/apk/res/android"
      Android: Required interpolator = "false"
      >
      Android: interpolator = "@ android: res/anim/accelerate_decelerate_interpolator"
      Android: fromalphi = "0.0"
      Android: toAlpha = "1.0"
      Android: duration= "2000"
      Android: repeatCount = "0"

      >


      Android: fromXDelta = "30"
      Android: toXDelta = "-80"
      Android: fromYDelta = "30"
      Android: toYDelta = "300"
      Android: duration= "2000"
      />


      However, in code mode, how can I get an instance loaded with multiple animations?

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.