Android Animation Implementation Switch Button animation (property animation translation animation) instance Code _android

Source: Internet
Author: User

Android animation to achieve switch button animation (property animation translation animation), recently done projects, according to the project needs, there is a function to achieve similar switch animation effect, through their own thinking and online search information, and finally resolved, here on the record:

In Android, some cool animations are really attractive places, let's see the Feast for the eyes, a good animation may improve the user's use of the software. In addition to animation, in Android support 3 kinds of animation: frame animation (frame Animation), motion Tween (Tween Animation) and attribute animation (property Animation), As for the differences between these kinds of animations are no longer introduced here, I hope that developers will be able to use the process to experience the difference between the two.

This article uses the attribute animation to complete, when speaking of the attribute animation, must mention Jakewharton writes Nineoldandroids animation storehouse, If your app needs to use the attribute animation below android3.0, then this library is very useful, if you only need to use in the high version, then directly use the animation API provided by the system.

First look at the animation effect to achieve: the finger moved up to the switch button, and then a click action, switch from off to open animation execution, while the fingers moved downward to the original position

Click on the picture to switch to the corresponding link to view the animation

use scenes for animations

When the user is directed to open a switch button on a function or to open a certain setting of the system, adding animation can increase the user's click-through rate and express the meaning more clearly.

before implementation, do the following preparatory work

1. Download the Nineoldandroids-2.4.0.jar library and put it in the Libs folder of the Android Studio Engineering directory

2. Introduction of the Build.gradle file

dependencies {Compile files (' Libs/nineoldandroids-2.4.0.jar ')}

3. Prepare the relevant picture resources

Next, encapsulate a custom control to implement the entire animation

Step one: First define a layout file Finger_switch_on_guide_layout.xml

<?xml version= "1.0" encoding= "Utf-8"?> <merge xmlns:android= "Http://schemas.android.com/apk/res/android"

 Android:id= "@+id/switch_anim_root" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" > <framelayout android:layout_width= "wrap_content" android:layout_height= "wrap_content" > <ImageView Andro Id:layout_width= "42DP" android:layout_height= "25DP" android:background= "@drawable/switch_container"/> <Ima Geview android:id= "@+id/switch_anim_circle_point" android:layout_width= "20DP" android:layout_height= "20DP" and roid:layout_marginleft= "2.5DP" android:layout_margintop= "2.5DP" android:background= "@drawable/switch_off_circle_ Point "/> </FrameLayout> <imageview android:id=" @+id/finger_switch "android:layout_width=" 34DP "Andro id:layout_height= "41DP" android:layout_marginleft= "5DP" android:layout_margintop= "25DP" android:background= "@ Drawable/finger_normal "/> </merge>

Layout file pre-cable length this way:

Step Two: Define the custom control (Switchonanimview) to implement the entire animation

Package Com.androidanimation.animationview;
Import Android.content.Context;
Import Android.os.Handler;
Import Android.util.AttributeSet;
Import Android.view.LayoutInflater;
Import Android.widget.FrameLayout;

Import Android.widget.ImageView;
Import COM.ANDROIDANIMATION.R;
Import Com.androidanimation.animations.BaseAnimatorListener;
Import Com.androidanimation.utils.ViewUtil;
Import Com.nineoldandroids.animation.Animator;
Import Com.nineoldandroids.animation.ObjectAnimator;

Import Com.nineoldandroids.view.ViewHelper;
 /** * Created by Popfisher on 2016/9/3.
 * * public class Switchonanimview extends Framelayout {private Handler Mhandler = new Handler ();
 /** switch in the middle of the circle View/private ImageView MCIRCLEPTIMGV;
 /** Finger View * * Private ImageView MFINGERIMGV;
 /** Finger Moving distance * * Private float mfingermovedistance;
 /** switch in the middle of the circle view need to move the distance * * Private float mcircleptmovedistance;
 private static final int finger_anim_duration = 300;

 private static final int circle_pt_anim_duration = 500; prIvate Boolean isstopanim = false;
 Public Switchonanimview {This (context, NULL);
  Public Switchonanimview (context, AttributeSet attrs) {Super (context, attrs);
  Loads the layout layoutinflater.from. Inflate (R.layout.finger_switch_on_guide_layout, this, true);
 Initview ();
  private void Initview () {MCIRCLEPTIMGV = (ImageView) Findviewbyid (r.id.switch_anim_circle_point);

  MFINGERIMGV = (ImageView) Findviewbyid (R.id.finger_switch);
  The following two distances are based on the UI layout to determine mfingermovedistance = viewutil.dp2px (GetContext (), 20f);
 Mcircleptmovedistance = viewutil.dp2px (GetContext (), 17.5f);
  /** * Start animation/public void Startanim () {Isstopanim = false;
  Restore the initial state Viewhelper.settranslationx (MCIRCLEPTIMGV, 0) before starting the animation;
  Mcircleptimgv.setbackgroundresource (R.drawable.switch_off_circle_point);
  Mfingerimgv.setbackgroundresource (R.drawable.finger_normal);
 Startfingerupanim ();
 }/** * Stop animation/public void Stopanim () {Isstopanim = true; }

 /* * Center punctuate view translation animation/private void Startcirclepointanim () {if (MCIRCLEPTIMGV = null) {return;
  } objectanimator Circleptanim = Objectanimator.offloat (MCIRCLEPTIMGV, "Translationx", 0, Mcircleptmovedistance);
  Circleptanim.setduration (circle_pt_anim_duration);
 Circleptanim.start (); /** * Finger up move animation/private void Startfingerupanim () {Objectanimator Fingerupanim = objectanimator.offloat (mfing
  ERIMGV, "Translationy", 0,-mfingermovedistance);
  Fingerupanim.setduration (finger_anim_duration);
    Fingerupanim.addlistener (New Baseanimatorlistener () {@Override public void Onanimationend (animator animator) {
    if (MFINGERIMGV = null | | mhandler = NULL) {return;
    }//Finger up animation to complete the setting of the finger view background for the Click state of the background mfingerimgv.setbackgroundresource (R.drawable.finger_click); After clicking the feeling of pausing for a moment, delay 200 milliseconds to perform other animations mhandler.postdelayed (new Runnable () {@Override public void run () {i F (mcircleptimgv = null | | mhandler = NULL) {RetuRn
      ////Set the center circle view background to switch on and start to pan right Mcircleptimgv.setbackgroundresource (r.drawable.switch_on_circle_point);
      Startcirclepointanim (); Delay 100 milliseconds start finger down Pan animation mhandler.postdelayed (new Runnable () {@Override public void run () {//Fingers Move down to start setting the position of the finger background to a normal state if (MFINGERIMGV!= null) {Mfingerimgv.setbackgroundresource (r.drawable.finger_normal
        );
       } startfingerdownanim ();
     }, 100);
   }, 200);
  }
  });
 Fingerupanim.start ();
  /** * Finger downward move animation/private void Startfingerdownanim () {if (MFINGERIMGV = null) {return;
  } objectanimator Fingerdownanim = Objectanimator.offloat (MFINGERIMGV, "Translationy",-mfingermovedistance, 0);
  Fingerdownanim.setduration (finger_anim_duration);
    Fingerdownanim.addlistener (New Baseanimatorlistener () {@Override public void Onanimationend (animator animator) { The finger moves down the animation completes, the entire animation process finishes, restarts the next process, loops the animation, the interval 1 seconds mhandler.postdelayed (New Runnable () {@Override public void run () {if (Isstopanim) {return;
     } startanim ();
   }, 1000);
  }
  });
 Fingerdownanim.start (); }
}

The final step: is to find a carrier to add Switchonanimview, call its Startanim method to perform animation, here in an activity to play this animation

Define activity Layout files activity_finger_switchon_anim.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:id=" @+id/activity_animation_main "
 android:layout_width=" Match_parent "
 Android : layout_height= "match_parent"
 android:gravity= "center"
 android:orientation= "vertical" >
 < Com.androidanimation.animationview.SwitchOnAnimView
  android:id= "@+id/switch_on_anim_view"
  android: Layout_width= "Wrap_content"
  android:layout_height= "wrap_content"/>

</LinearLayout>

Define and implement activity:fingerswitchonanimactivity

Package com.androidanimation;

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;

Import Com.androidanimation.animationview.SwitchOnAnimView;

public class Fingerswitchonanimactivity extends activity {

 private Handler Mhandler = new Handler ();
 Private Switchonanimview Mswitchonanimview;

 @Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_finger_switchon_anim);
  Mswitchonanimview = (Switchonanimview) Findviewbyid (R.id.switch_on_anim_view);
 Mhandler.postdelayed (New Runnable () {
   @Override public
   void Run () {
    mswitchonanimview.startanim ();
   }
  };
}    

Animation Implementation Summary:

  Mastering the Android animation is not difficult, how to implement some complex animation, here summed up the implementation of a number of complex animation steps.

  1. Animation decomposition: any complex animation can be decomposed into a combination of many atomic animation

  2. Animation Connection Opportunity Analysis: complex animation decomposed into many atomic animation , to reconnect

This is actually the timing of the implementation of each atom animation, who first or at the same time execute

  3. To achieve atomic animation: the dismantling of the atomic animation in turn to achieve

  4. Animation assembly: The above are ready, the atomic animation in accordance with a certain regularity of the Assembly series, the entire complex animation began to work

Atomic animation: This article refers to an animation that can no longer be split

  For the animations in this article, animations can be divided into four:

A. Move your finger up the animation

B. Finger Click action (this is not an animation, it can be used as a simple animation bar)

C. Switch button origin to right translate animation

D. Translate your finger down to the animation.

 The timing of this animation is:

A first executes, a execution completes immediately after executing b,b execution completes waits for 200ms to execute C (manifests the Click Effect)

C Execute Start 100ms and start execution D

Animation decomposition and animation to join the timing analysis is not easy, because with the naked eye sometimes can not be observed, so play the animation to slow down, if you still can't see it, it is best to find the company's UI colleagues to assist analysis. Because we can easily distinguish between translation animation, scaling animation This simple, but we can not distinguish between that kind of sine algorithm animation or other algorithms to control the animation. The animation in this article is relatively simple and easy to implement, but the idea is exactly the same.

SOURCE Download Address: Https://github.com/PopFisher/AndroidAnimationDemos

Thank you for reading, I hope to help you, thank you for your support for this site!

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.