How to implement a 3D flip animation and 3D page flipping in Android

Although my site is in german, I write this text in english, because it is coding related.
This example should be compatible with Android 2.2 and higher.

Inspired by this post I extended the example by a Flip3DAnimator which tracks user touches and allows to animate without instantiating new objects. Therefore it avoids garbage collection.

Let’s begin with the Flip3DAnimation which I modified slightly. To be usable in the onTouch() method without instantiating a new object I added the update() method. I also added a callback interface to implement the page flipping effect.

Look here for a detailed explanation of this class.

Now the complicated part – the Flip3DAnimator which sets an OnTouchListener to the desired view and takes care of the touch events. The animator implements the Flip3DAnimationCallback an handles it appropriatly. You can uncomment the Log lines to see the process and understand the behavior. I will not explain everything in detail, but there are some helpfull javadocs. Mainly the OnTouchListener analyses the touch events and calculates the angle of the view dependent on the touch events. Then it applies a Flip3DAnimation to the desired view. When the touch ends a final animation is applied to the view, flipping it with the resulting velocity to 0 degrees. In case the user didn’t flip over 90 degrees the animation is applied in two stages. the first stage animated to 90 degrees (reports this to the Flip3DAnimatorCallback) and the second to 0. The Flip3DAnimatorCallback reports important events for handling page flipping.

In a test project I use this technique and a ton of more code with layout XMLs to achieve a book filling up the whole display. After each full flip the new pages are loaded (left covered page, left page, right page and right covered page).

Finally make a view flippable by instantiating the animator. Call for example  mFlipAnimatorLeft = new Flip3dAnimator(mFlipViewLeft, this, PageSide.PAGE_SIDE_LEFT, 0.9f); in you onCreate() or onCreateView() if you use fragments.

Dont‘ forget to implement the callback. It could look like this.

If you have any questions or critics leave a comment below. Maybe I’ll answer it…

Schreib einen Kommentar