We all love animations, right? Well I will show you a simple technique for creating a cool effect. Not to go too much into detail, this task is simple. On click of an image button start an animation. For those who don't know, to make an AnimationDrawable animation on android, you will need couple of things.
- Images for each frame of course
- XML file where you will define images of each frame contained in the animation and the duration for the each frame.
- In your layout XML file, attach the name of the XML animation file to the src tag ("android:src=name_of_animation_xml")
- Reference your AnimationDrawable in the java source file, and just call start(). The one thing you need to be careful of are the threads. Any kind of animation needs to run in a separate thread from the main thread.
private buttonAnimation= (AnimationDrawable)button.getDrawable(); button.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) { buttonAnimation.selectDrawable(0); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub buttonAnimation.stop(); buttonAnimation.start(); } }).start(); } else { buttonAnimation.selectDrawable(0); } return false; } });
Yes, you are correct if you are thinking, why the hell is he using the onTouch event? Well, an onClick event happens when the user already clicked and the animation will happen when the user releases his/hers sticky fingers. So you need to start the animation on user's first contact.
What exactly is going on here? Patience young grasshopper :). Basics of the above code is, Get the drawable(animation XML) from the ImageButton button, ask if the user touched the button and start the animation. Simple, but effective.
buttonAnimation.selectDrawable(0)
sets the animation to the first frame, or simply put resets the animation. stop() and start() methods are self explanatory so I won't go deep into that.
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) { // do stuff } else { // do other stuff }
this is the important part. it basically asks if user touched the button. In other cases, like, user slides off the button, users lets go the button and other stuff the animation resets and sets on the first frame.
So hope this was helpful to you,
Until next time
No comments:
Post a Comment