Android animation--Add shopping cart animations (pits and optimizations)

Source: Internet
Author: User

We often see animations that add to a shopping cart, whether it's a treasure or a certain east. is to click on a product, the product into a small thumbnail to move to the shopping cart inside.

Today, suddenly think of the original made so that an animated stickers for everyone to learn.

Look first. GIF tools can't bear to look straight, the real operation is a very smooth parabolic line.


First of all, we need a few things to see.
1, start position of animation
2, the end position of the animation
3, animated Moving pictures (here in order to simply use a small dot, you can change the thumbnail image of the product)
4, how to deal with the radian of animation
5, where to manipulate the data after the animation is complete
6, how to create multiple animations when you click the picture animation continuously

Then we'll solve the problem.
The Prime Minister defines a Shoppingcartanim class that defines several necessary constants

* * Shopping Cart Add animation */ Public classShoppingcartanim {PrivateImageView buyimg;//Play the animated reference ImageView    Private int[] Start_location =New int[2];//This is the x and Y coordinates used to store the start position of the animation;    Private int[] End_location =New int[2];//This is the x and Y coordinates used to store the end position of the animation;    Private StaticHandler Mthreadhandler;//Non-UI thread callbacks for data manipulation     PublicViewGroup Root;//Animation layer    Private StaticThread thread;//Non-UI threads for data manipulation}

Where I define a thread and a handler, the purpose is to do something after the animation does not affect the next click Animation. So put it in a non-UI ' thread.

This way, when we click the animation in succession, the animation will not appear because the last data was not finished.

Instantiating a child thread in a static method

Static{thread =NewThread (NewRunnable () {@Override             Public void Run() {//Non-UI thread                //Perform the data processing after the animation is done, such as adding items to the shopping cart                //Send message to UI threadMthreadhandler.sendemptymessage (0);        }        }); Mthreadhandler =NewHandler () {@Override             Public void Handlemessage(Message msg) {Switch(msg.what) { Case 0://The thread should be shut down in time after OperationThread.Interrupt ();//ui Operation                        //This is done after the animation, such as shopping cart jitter animation                         Break; }            }        };

Defining Construction methods

publicShoppingCartAnim(Activity activity) {        new ImageView(activity);//buyImg是动画的图片        buyImg.setImageResource(R.drawable.sign);// 设置buyImg的图片        //buyImg.setImageBitmap(bitmap);//也可以设置bitmap,可以用商品缩略图来播放动画        root = (ViewGroup) activity.getWindow().getDecorView();//创建一个动画层        root.addView(buyImg);//将动画参照imageview放入    }

Defines a method for placing ImageView in the animation layer and placing it at the starting coordinate position

    /** * Add an image image to the animation layer and place it in the start coordinate position * * @param view of the video playback animation * @param location start position * @return * *    PrivateViewAddviewfromanimlayout(View view,int[] location) {intx = location[0];inty = location[1]; Framelayout.layoutparams LP =NewFramelayout.layoutparams (FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WR        Ap_content);        Lp.leftmargin = x;        Lp.topmargin = y; VIEW.SETLAYOUTPARAMS (LP);returnView }

We pass in a imageview and starting coordinates that need to be played, we get the specific starting position of this imageview, we can use it directly when playing the animation. Because the location of the problem has been adjusted in it.

The most important part
Provides an externally invoked interface to the starting reference target and end reference target of the animation

 Public void Startanim(View Startview, view Endview) {//This is the x, y coordinate (which is also the coordinate at which the animation starts) to get the starting target view in the screen.Startview.getlocationinwindow (start_location);//Shopping cart End locationEndview.getlocationinwindow (end_location);//Create a new view of the animated picture and the starting coordinates to play the animation        //Add an image image to the animation layer        /** Why not just send a picture here, but send a imageview?         * Because I'm doing this to clone animation playback controls, why clone?         * Because if the user clicks to add the shopping cart continuously, if only uses one ImageView to play the animation, this animation will return to the original point to play again after having not finished playing.         * And if clone a ImageView to play, then this animation has not finished, the user click Add Shopping cart after we still clone a new ImageView to play.         * So the animation will appear several points instead of a point has not been played and retracted back. * Speaking of the popular point, is to rely on this method, the reference object and the starting position to wear, get a clone of the object to play the animation * *View Run_view = Addviewfromanimlayout (buyimg, start_location);//Calculate Displacement        intEndX = end_location[0]-start_location[0];intEndY = end_location[1]-start_location[1];//Translate animation to draw X-axis 0 to the end of the x-axisTranslateanimation Translateanimationx =NewTranslateanimation (0, EndX,0,0);//Set linear InterpolatorTranslateanimationx.setinterpolator (NewLinearinterpolator ());//The number of times the animation repeatsTranslateanimationx.setrepeatcount (0);//Set the animation to disappear after playing, terminate the fillTranslateanimationx.setfillafter (true);//Translate animation to draw y-axisTranslateanimation Translateanimationy =NewTranslateanimation (0,0,0, EndY); Translateanimationy.setinterpolator (NewAccelerateinterpolator ()); Translateanimationy.setrepeatcount (0); Translateanimationx.setfillafter (true);//Put two animations in the animation playback collection        //Set False to make each sub-animation use its own interpolatorAnimationset set =NewAnimationset (false);//Set the animation to disappear after playing, terminate the fillSet.setfillafter (false);        Set.addanimation (Translateanimationy);        Set.addanimation (Translateanimationx); Set.setduration ( -);//The execution time of the animation        /** * When the animation starts to play, the reference object is displayed, and if not displayed, the animation will not see anything. * Because no matter how many times the user clicks the animation, the ImageView is played from the reference object Buyimg in Clone * */Buyimg.setvisibility (view.visible); Run_view.startanimation (set);//Animation listener EventsSet.setanimationlistener (NewAnimation.animationlistener () {//start of animation            @Override             Public void Onanimationstart(Animation Animation) {            }//Repeat in animation            @Override             Public void onanimationrepeat(Animation Animation) {//TODO auto-generated method stub}//End of animation            @Override             Public void Onanimationend(Animation Animation) {//After the animation is played, the reference object will be hiddenBuyimg.setvisibility (View.gone);Access data after//endThread.Start ();    }        }); }

I have explained the code in detail in every sentence.
You can also add rotation zoom to the animation collection, which is also very simple.

There is also a detailed operation, which is in the activity:

    /**     * 内存过低时及时处理动画产生的未处理冗余tg     */    @Override    publicvoidonLowMemory() {        // TODO Auto-generated method stub        ifnull) {            try {                cartAnimation.root.removeAllViews();            catch (Exception e) {                e.printStackTrace();            }            super.onLowMemory();        }    }

The main part has been completed.
See how it is called.

CartAnimation cartAnimation = new CartAnimation(getActivity());            cartAnimation.setAnim(startImageview, shoppingCartView);

No return value is required and you need to manipulate the data to be fully operational in the thread.

OK, this is the add Shopping cart animation, you can play on top of the imagination to add more cool animation.

But let's summarize the details. (Well, the details are important!) )

1, the animation is played based on activity, how to consider memory consumption issues
2, how to manipulate the data after the animation play to make the animation not Dayton
3, Continuous Click Animation How to make an animation not only run the example

The main problem I have solved, you just have to play with the imagination to create more complex cool animations.

Android animation--Add shopping cart animations (pits and optimizations)

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.