Android Animation II: View Animation

Source: Internet
Author: User

As the previous blog, "One of the Android animation: drawable Animation" said, Android animation is mainly divided into three parts, the previous blog has been explained drawable Animation usage, that is, frame by picture display, Often used to dynamically display a progress animation, which is the most frequently occurring application scenario. Next, we'll step through this article to introduce the view Animation.

View Animation is also a lot of books that we usually say tweened Animation (someone translated as tweened animation). View animation is divided into 4 categories: Alphaanimation,rotateanimation,scaleanimation,translateanimation, respectively, corresponding to the transparency, rotation, size, displacement four kinds of changes.

The effect of View animation is determined by four factors: 1) initial state; 2) end State; 3) duration; 4) interpolator. So to define a view Animation, you just define the above four factors, and the process in the middle is automatically calculated by the system. The first 3 factors are easy to understand, the fourth factor interpolator more special, the word does not know how to translate more suitable, many books translation is very strange. Interpolator is the change in the speed at which the animation is determined. For example: You move a button from the left side of the screen to the right side of the screen. Can let it always accelerate forward, or slow down and then slow down, this is the role of interpolator play, the specific use of the method below will say, first of all, from the simple.

Like drawable animation, defining a view animation can be done in code or in an XML file. Let's start with the simplest example of moving, rotating, zooming, and darkening a HelloWorld string, respectively, using code implementations and XML files. First implemented in code.

First create a new project: Viewanimationdemo, and create a new layout file: Animationjavacode.xml, as follows:

Viewanimationdemo\res\layout\animationjavacode.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ".        Mainactivity "> <textview android:id=" @+id/translation "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_marginbottom= "50DP" android:text= "I Want to move"/> <Tex TView android:id= "@+id/rotate" android:layout_width= "wrap_content" android:layout_height= "Wrap_conten T "android:layout_below=" @id/translation "android:layout_marginbottom=" 50DP "android:text=" I want to rotate "/&gt    ;    <textview android:id= "@+id/scale"    Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/rotat E "android:layout_marginbottom=" 50DP "android:text=" I Want to Grow "/> <textview android:id=" @+id/alph A "android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:layout_below=" @id /scale "android:layout_marginbottom=" 200DP "android:text=" I want to darken "/> <button android:id=" @+id/ Fire "android:layout_width=" Match_parent "android:layout_height=" 50DP "android:layout_below=" @id/alph A "android:text=" movement "/></relativelayout>"

The XML layout file corresponds to the following activity:

Viewanimationdemo/src/com/csdn/viewanimationdemo/animcodeactivity.java

public class Animcodeactivity extends Activity {private TextView translation;private TextView rotate;private TextView SCA    Le;private TextView alpha;private button button;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);                Setcontentview (R.layout.animationjavacode);        Translation = (TextView) Findviewbyid (r.id.translation);        Rotate = (TextView) Findviewbyid (r.id.rotate);        Scale = (TextView) Findviewbyid (R.id.scale);        Alpha = (TextView) Findviewbyid (R.id.alpha);                Button = (button) Findviewbyid (R.id.fire); Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stub//1&2: Determine the starting state, end state translateanimation Tanim = new Translateanimation (0, 400, 0, 0);//Lateral Displacement 400 units rotateanimation Ranima = new Rotateanimation (0, 70);//clockwise rotation 70 degrees scaleanimation Sanima = new ScaleaniMation (0, 5, 0, 5);//zoom in 5 times times, vertical magnification 5 times times alphaanimation Aanima = new Alphaanimation (1.0f, 0.0f);//from full opacity to full transparent//3: Determine duration tanim.setduration (ranima.setduration), sanima.setduration (+), Aanima.setduration (2000);//4: Determine Interpolatortanim.setinterpolator (new Acceleratedecelerateinterpolator ());//Start Animation translation.startanimation (            Tanim); rotate.startanimation (Ranima); scale.startanimation (Sanima); alpha.startanimation (AAnima);}); }}

It is not difficult to see from the code, first determine the starting state and end state of the animation, and then set the duration through Setduration (2000), if the duration is not set here, will default to 30MX, the basic naked eye can not see. Finally we set up a interpolator, where the effect is that the animation slows down first and then slows down. The default state is constant. Yes, the basic usage of interpolator is so easy. The above code is as follows:


Next explains how to use XML to define the animation, according to the Android official website introduction, defines the view animation the XML file format as follows:

<?xml Version= "1.0" encoding= "Utf-8"? ><set xmlns:android= "Http://schemas.android.com/apk/res/android" Android: Interpolator= "@[package:]anim/interpolator_resource" android:shareinterpolator=["true" | "False" > <alpha android:fromalpha= "float" android:toalpha= "float"/> <scale andro        id:fromxscale= "float" android:toxscale= "float" android:fromyscale= "float" android:toyscale= "float"        android:pivotx= "float" android:pivoty= "float"/> <translate android:fromxdelta= "float" Android:toxdelta= "float" android:fromydelta= "float" android:toydelta= "float"/> <rotate android     oid:fromdegrees= "float" android:todegrees= "float" android:pivotx= "float" android:pivoty= "float"/> <set> </set></set> 

The file can only have one root node, which could be <set>,<alpha>,<scale>,<translate>,<rotate> Nodes can contain child nodes, which can contain <set>,<alpha>,<scale>,<translate>,<rotate&gt, and so on.

The above two tag attributes that need to be explained are Android:interpolator and Android:shareinterpolator, which represent the interpolator you are using, either the system comes with or it can be customized. The latter represents whether the interpolator is shared with the child nodes. The properties of other sub-tags are easy to understand, basic look at the property name can understand, in addition to two of them, Android:pivotx and Android:pivoty, we know that pivot means axis meaning, so these two properties defined is the axis position of the animation changes, The default is the upper-left corner, and when we assign both of them to 50%, the axis of change is centered.

Next, write a specific example, as below, or in the project just now. In general we put the XML file of the definition animation in the Res/anim directory, first we create a new Anim folder, and then create a new XML file, as follows:

Viewanimationdemo/res/anim/myanim.xml

<set xmlns:android= "Http://schemas.android.com/apk/res/android" android:shareinterpolator= "false" > <        Scale android:interpolator= "@android: Anim/accelerate_decelerate_interpolator" android:fromxscale= "1.0"        android:toxscale= "1.4" android:fromyscale= "1.0" android:toyscale= "0.6" android:pivotx= "50%" Android:pivoty= "50%" android:fillafter= "false" android:duration= "+"/> <set android:inter Polator= "@android: Anim/accelerate_interpolator" android:startoffset= "> <scale android:            fromxscale= "1.4" android:toxscale= "0.0" android:fromyscale= "0.6" android:toyscale= "0.0"            "50%" android:pivoty= "50%" android:duration= "android:pivotx="/> <rotate android:fromdegrees= "0" android:todegrees= "android:toyscale=" 0.0 "android:p ivotx= "50%" Android:Pivoty= "50%" android:duration= "/>" </set></set> 

The above examples are as follows:


In the above code, there is only one root node <set> it has two child nodes <scale> and <set> and then the child nodes <set> has two of its own child nodes <scale> and < Rotate>. Explain some of the label properties that you haven't seen above.

Andoird:fillafter: In the previous example, after the end of our animation HelloWorld back to the original state, by setting Fillafter to True, the animation will remain the end of the state, but, as the previous blog " One of the Android animations: Drawable Animation said that the animation effect of the View Animation is drawn, not the component really moved, we will continue to discuss this issue. Now you only need to know that when Fillafter is set to True, the animation will remain in the end state, which is mostly applied to the design of successive animations.

Startoffset: This property defines how long the animation will be delayed, and with this property setting, we can design some animations that occur before and after the sequence, except, of course, other animations have to be set Fillafter to true in addition to the last one that occurs.

Interpolator: Here we use the system's own interpolator

Next we define a layout file, the layout file has only one picture, a button, click the button to trigger the image animation, the layout file is relatively simple, not listed here. How to start the animation in the activity code corresponding to the layout file, the code is as follows:

Viewanimationdemo/src/com/csdn/viewanimationdemo/animaxmlactivity.java

public class Animaxmlactivity extends Activity {private Button btn;private ImageView img; @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); SetContentView ( R.layout.activity_anima_xml); btn = (Button) Findviewbyid (R.ID.XML_BTN); img = (ImageView) Findviewbyid ( R.ID.XMLANIMIMG); Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method Stubanimation Anim = Animationutils.loadanimation (Animaxmlactivity.this, R.anim.myanim); Img.startanimation (Anim);}});}}

The above code is easy to understand and we generally use animationutils to read the animations defined in the XML file.

So far, the basic knowledge about view animation has basically been covered, then write a concrete example of practice, to achieve the frequently seen slide-off function, such as NetEase news:



This side-by-side effect is not difficult, and many people use asynctask threads, but as a result you will find that there are sometimes noticeable stuttering, but if you use animation will be much smoother. We then implement this feature:

Create a new project first: Swipewithanim. and create a new layout file Activity_main.xml, as follows

Swipewithanim/res/layout/activity_main.xml

<framelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:context =". Mainactivity "> <view android:id=" @+id/content "android:layout_width=" Match_parent "Android:        layout_height= "Match_parent" android:background= "#e23451"/> <linearlayout android:id= "@+id/menu"        Android:layout_width= "400DP" android:layout_height= "match_parent" android:layout_gravity= "left" android:layout_marginleft= " -380DP" android:orientation= "horizontal" > <view android:layout _width= "0DP" android:layout_height= "Match_parent" android:layout_weight= "1" android:backg            round= "#eeeee1"/> <view android:id= "@+id/dragarea" android:layout_width= "20DP"     android:layout_height= "Match_parent"       android:background= "#00000000"/> </LinearLayout></FrameLayout> 

The contents of the screen display content, the left side of the menu menus, the knowledge will be 20DP transparent parts on the left side of the screen to trigger the Ontouch event. The activity code corresponding to the XML file is as follows:

Swipewithanim/src/com/csdn/swipewithanim/mainactivity.java


public class Mainactivity extends Activity {private View menu;private final static int show_menu = 1;private final static int hide_menu = -1;private int swipe_tag = show_menu;private int max_menu_margin = 0;private int min_menu_margin;private f Loat beginx;private float latestx;private float diffx;private float latestmargin;private framelayout.layoutparams lp;/* * (non-javadoc) * * @see android.app.activity#oncreate (android.os.Bundle) */@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_main); menu = Findviewbyid (r.id.menu); LP = (Framelayout.layoutparams) Menu.getlayoutparams (); min_menu_margin = Lp.leftmargin;menu.setontouchlistener (new Ontouchlistener () {@ Overridepublic boolean OnTouch (View V, motionevent event) {//TODO auto-generated method Stubint action = Motioneventcompa T.getactionmasked (event); switch (action) {Case MotionEvent.ACTION_DOWN:beginX = Event.getx(); Break;case MotionEvent.ACTION_MOVE:latestX = Event.getx ();d iffx = Latestx-beginx;swipe_tag = diffx > 0? Show_menu:hide_menu;latestmargin = Lp.leftmargin + diffx;if (Latestmargin > min_menu_margin&& latestMargin & Lt Max_menu_margin) {lp.leftmargin = (int) (latestmargin); menu.setlayoutparams (LP);} Break;case MotionEvent.ACTION_UP:TranslateAnimation tanim;if (Swipe_tag = = show_menu) {Tanim = new Translateanimation (0 , Max_menu_margin-latestmargin, 0, 0); Tanim.setinterpolator (new Decelerateinterpolator ()); tanim.setduration (800); Menu.startanimation (Tanim);} else {Tanim = new Translateanimation (0, min_menu_margin-latestmargin, 0, 0); tanim.setduration (800); Menu.startanimation (Tanim);} At the end of the animation, move the menu position so that the menu really moves. Tanim.setanimationlistener (New Animationlistener () {@Overridepublic void Onanimationstart (Animation Animation) {// Todo auto-generated method stub} @Overridepublic void Onanimationrepeat (Animation Animation) {//Todo auto-generated Method stub} @Overridepublic VOID Onanimationend (Animation Animation) {//TODO auto-generated method stubif (Swipe_tag = show_menu) {Lp.leftmargin = ma X_MENU_MARGIN;MENU.SETLAYOUTPARAMS (LP);} else {lp.leftmargin = MIN_MENU_MARGIN;MENU.SETLAYOUTPARAMS (LP);} Menu.clearanimation ();}}); break;} return true;}});}}

As the code above, listen to the menu's Ontouch event, then move the menu according to the moving distance, and when the finger is picked up, start the animation so that the move proceeds to the end. As we mentioned above, the View animation is just the effect of the drawing, the animation component is not really moving, then in order to solve this problem, we listen to the Animationlistener, at the end of the animation, the position of the menu to the end of the animation position, This will successfully move the menu. As a result of the software relationship, it looks like Kaka, and the test on the real machine is completely smooth.



Finally, attach the two source code before and after this blog post:


Viewanimationdemo

Swipewithanim




Android Animation II: View Animation

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.