In this post we are going to look at how to create a 3D flip animation, with a FrameLayout.

In the first few posts I've written on Android and animations we have only looked at the predefined animations supplied in theandroid.view.animationspackage. In fact we've only used the translate animation, but as I've mentioned before there are also rotate, scale and alpha animations.


In this tutorial i want to take a further look at animations and how we can created our own custom animations using the Android library. I've going to base the tutorial on some of the examples that can be found in the samples folders that are downloaded with the android SDK. These are some great examples, but unfortunately they seem to lack a little on documentation and explanation as to how, and what, the code is doing. Hopefully by the end of this tutorial things should be a little clearer.
Before we start here's an example of the end result of our 3d flip:
So lets get started. First Create a new Android project in Eclipse with these setting: Project name: Flip3d Application Name: Flip3d package name: com.example.flip3d Activity: Flip3d
I've used some firefox image icons to animate, they are part of a very good and free icon set that can be found here . If you just want the images i've used they can be found here and here . Download these images and place them in the res/drawable folder of the Flip3d project.

Lets start with defining a layout that we can use. As I mentioned we are going to use a FrameLayout. As with the ViewFlipper the FrameLayout can contain a number of child views, but unlike ViewFlipper, FrameLayout stacks it's child views on top of each other with the most recent added child on top. Initially without any intervention all the child views of the FrameLayout are visible, but don't worry about that for now, we will solve this at a later stage. In the FrameLayout we will define two child views, these are the views that we will animate between. In res/layout edit the main.xml file so that it looks like this:

<?xmlversion="1.0"encoding="utf-8"?> 2. <FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android" 3. android:id="@+id/container" 4. android:layout_width="fill_parent" 5. android:layout_height="fill_parent"> 6. <includeandroid:id="@+id/notelist"layout="@layout/first_view"/> 7. <includeandroid:id="@+id/notelist"layout="@layout/second_view"/> 8. </FrameLayout>
This is the frame layout and we've specified that it contains two child views, first_view and second_view. Lets Create these views. In res/layout create two files first_view.xml and second_view.xml. The first view file needs to look like this:
<RelativeLayoutandroid:id="@+id/Layout01" 02. android:layout_width="fill_parent" 03. android:layout_height="fill_parent" 04. xmlns:android="http://schemas.android.com/apk/res/android"> 05. <mageView 06. android:layout_centerHorizontal="true" 07. android:layout_centerVertical="true" 08. android:layout_width="wrap_content" 09. android:id="@+id/ImageView01" 10. android:layout_height="wrap_content" 11. android:src="@drawable/firefox" 12. > 13. </ImageView> 14. </RelativeLayout> And second_view.xml contains this xml:

<RelativeLayoutandroid:id="@+id/Layout02" 02. android:layout_width="fill_parent" 03. android:layout_height="fill_parent" 04. xmlns:android="http://schemas.android.com/apk/res/android"> 05. <ImageView 06. android:layout_centerHorizontal="true" 07. android:layout_centerVertical="true" 08. android:layout_width="wrap_content" 09. android:id="@+id/ImageView02" 10. android:layout_height="wrap_content" 11. android:src="@drawable/firefox_alt" 12. > 13. </ImageView> 14. </RelativeLayout>

These two views are almost identical and only contain two different images that we will flip between.Now we have our layouts defined we need to write some Java to implement our 3d flip. Create a Java class called Flip3dAnimation in the com.example.flip3d package and cut and paste in this code:

packagecom.example.flip3d; 02. 03. importandroid.graphics.Camera; 04. importandroid.graphics.Matrix; 05. importandroid.view.animation.Animation; 06. importandroid.view.animation.Transformation; 07. 08. publicclassFlip3dAnimationextendsAnimation { 09. privatefinalfloatmFromDegrees; 10. privatefinalfloatmToDegrees; 11. privatefinalfloatmCenterX; 12. privatefinalfloatmCenterY; 13. privateCamera mCamera; 14. 15. publicFlip3dAnimation(floatfromDegrees,floattoDegrees, 16. floatcenterX,floatcenterY) { 17. mFromDegrees = fromDegrees; 18. mToDegrees = toDegrees; 19. mCenterX = centerX; 20. mCenterY = centerY; 21. } 22. 23. @Override 24. publicvoidinitialize(intwidth,intheight,intparentWidth,intparentHeight) { 25. super.initialize(width, height, parentWidth, parentHeight); 26. mCamera =newCamera(); 27. } 28. 29. @Override 30. protectedvoidapplyTransformation(floatinterpolatedTime, Transformation t) { 31. finalfloatfromDegrees = mFromDegrees; 32. floatdegrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); 33. 34. finalfloatcenterX = mCenterX; 35. finalfloatcenterY = mCenterY; 36. finalCamera camera = mCamera; 37. 38. finalMatrix matrix = t.getMatrix(); 39. 40. camera.save(); 41. 42. camera.rotateY(degrees); 43. 44. camera.getMatrix(matrix); 45. camera.restore(); 46. 47. matrix.preTranslate(-centerX, -centerY); 48. matrix.postTranslate(centerX, centerY); 49. 50. }

51.}

Custom Animation class
This class extends the Animation class and implements the applyTransformation method. Each Animation has a transformation object that Defines the transformation to be applied at a point in time of the Animation. When this animation is running the applyTransformation method will be called a number of times to allow us to calculate the transformation to be applied. Each time applyTransformation is called the interpolation value passed in will be increased slightly starting at 0 and ending up at 1. So our float 'degree' at line LINE NUMBER will increase slightly each time this method is called.
The main steps that happen in the applyTransformation are:
Calculate the degrees rotation for the current transformation
Get the tranformation matrix for the Animation
Generate a rotation matrix using camera.rotate(degrees)
Apply that matrix to the Animation transform
Set a pre translate so that the view is moved to the edge of the screen and rotates around it centre and not it's edge
Set a post translate so that the animated view is placed back in the centre of the screen.

Camera in android.graphics
You can see that we also use the android.graphics.Camera class, don't get this confused with camera class in android.hardware which is used to control the Camera on the android device. The Camera class in the android.graphic package is very different, it is used to calculate 3d transformations that can then be applied to animations. This Camera class represents a virtual view as if we were looking at our Android views through a camera. As we move our virtual camera to the left , we have the effect of the android view moving to the right , and if we rotate our virtual camera, we have the effect of rotating our Android view. Here the Camera class is use to calculate a rotate transformation about the Y axis, it does this every time the applyTransformation method is called and so gives each incremental transformation that is needed to give a smooth rotation effect. Camera uses transformation matrices to store and calculate transforms. It's not really necessary to have an in depth knowledge of how transformation matricies work, but a good article on them can be found here . The article is based around flash, but the same principles apply.
Now that we've got our rotation animation we need to come up with a plan of how to use it. We currently have two images but just rotating these isn't going to give us the effect we want. So what we need to do is hide the second image and display only the first. We will then rotate this image through 90 degree until it's edge on and we can no longer see it. At this point we will make the first image invisible and the second image visible, we will start the animation of the second image at a 90 degree angle and then roatate round until it is fully visible. To go back from the second to the first image we will just reverse the process.
We'll start with our main Activity class Flip3d.java: packagecom.example.flip3d; 02. 03. importandroid.app.Activity; 04. importandroid.os.Bundle; 05. importandroid.view.View; 06. importandroid.view.animation.AccelerateInterpolator; 07. importandroid.widget.ImageView; 08. 09. publicclassFlip3dextendsActivity { 10. 11. 12. privateImageView image1; 13. privateImageView image2; 14. 15. privatebooleanisFirstImage =true; 16. 17. 18. /** Called when the activity is first created. */ 19. @Override 20. publicvoidonCreate(Bundle savedInstanceState) { 21. super.onCreate(savedInstanceState); 22. setContentView(R.layout.main); 23. 24. image1 = (ImageView) findViewById(R.id.ImageView01); 25. image2 = (ImageView) findViewById(R.id.ImageView02); 26. image2.setVisibility(View.GONE); 27. 28. image1.setOnClickListener(newView.OnClickListener() { 29. publicvoidonClick(View view) { 30. if(isFirstImage) { 31. applyRotation(0,90); 32. isFirstImage = !isFirstImage; 33. 34. }else{ 35. applyRotation(0, -90); 36. isFirstImage = !isFirstImage; 37. } 38. } 39. }); 40. } 41. 42. privatevoidapplyRotation(floatstart,floatend) { 43. // Find the center of image 44. finalfloatcenterX = image1.getWidth() /2.0f; 45. finalfloatcenterY = image1.getHeight() /2.0f; 46. 47. // Create a new 3D rotation with the supplied parameter 48. // The animation listener is used to trigger the next animation 49. finalFlip3dAnimation rotation = 50. newFlip3dAnimation(start, end, centerX, centerY); 51. rotation.setDuration(500); 52. rotation.setFillAfter(true); 53. rotation.setInterpolator(newAccelerateInterpolator()); 54. rotation.setAnimationListener(newDisplayNextView(isFirstImage, image1, image2)); 55. 56. if(isFirstImage) 57. { 58. image1.startAnimation(rotation); 59. }else{ 60. image2.startAnimation(rotation); 61. } 62. 63. } 64. }
In the main activity class we have the usual onCreate method. In this method we get references to the two images that we are displaying. Here we also set the visibility of our second image to View.Gone. The final thing to be done in onCreate is to set up a click listener for our fist image (we don't need a click listener for the second image). In the click listener we have a boolean, isFirstImage, which tells us which image is currently visible, if it's true the first image is visible and if false the second image is visible. Depending on which image is visible, we call the applyRotation method with different start and end values, since we rotate the first image in a different direction to the second image.

The applyRotation method is fairly straight forward, we find the centre of our image, create a new instance of our Flip3dAnimation, and apply and start it for the visible image. Well, there's a little more yet... As you may have already noticed we've only done half the animation here, from 0 to 90 degrees, we still have another 90 degrees to go, and we still have to swap the images over half way through. So this is were we need an Animation listener, which we are going to call DisplayNextView. Create a class of this name and paste in this code:
packagecom.example.flip3d; 02. 03. importandroid.view.animation.Animation; 04. importandroid.widget.ImageView; 05. 06. publicfinalclassDisplayNextViewimplementsAnimation.AnimationListener { 07. privatebooleanmCurrentView; 08. ImageView image1; 09. ImageView image2; 10. 11. publicDisplayNextView(booleancurrentView, ImageView image1, ImageView image2) { 12. mCurrentView = currentView; 13. this.image1 = image1; 14. this.image2 = image2; 15. } 16. 17. publicvoidonAnimationStart(Animation animation) { 18. } 19. 20. publicvoidonAnimationEnd(Animation animation) { 21. image1.post(newSwapViews(mCurrentView, image1, image2)); 22. } 23. 24. publicvoidonAnimationRepeat(Animation animation) { 25. } 26. }
The DisplayNextView Animation Listener is very simple and just listens for the end of the rotate animation, Since out first rotate animation only goes from 0 to 90 onAnimatonEnd method will be called when our first image is at 90 degrees. So now we need to Swap the images and this is were out SwapViews class comes in. So create a class called swap views and paste in this code:
packagecom.example.flip3d; 02. 03. importandroid.view.View; 04. importandroid.view.animation.DecelerateInterpolator; 05. importandroid.widget.ImageView; 06. 07. publicfinalclassSwapViewsimplementsRunnable { 08. privatebooleanmIsFirstView; 09. ImageView image1; 10. ImageView image2; 11. 12. publicSwapViews(booleanisFirstView, ImageView image1, ImageView image2) { 13. mIsFirstView = isFirstView; 14. this.image1 = image1; 15. this.image2 = image2; 16. } 17. 18. publicvoidrun() { 19. finalfloatcenterX = image1.getWidth() /2.0f; 20. finalfloatcenterY = image1.getHeight() /2.0f; 21. Flip3dAnimation rotation; 22. 23. if(mIsFirstView) { 24. image1.setVisibility(View.GONE); 25. image2.setVisibility(View.VISIBLE); 26. image2.requestFocus(); 27. 28. rotation =newFlip3dAnimation(-90,0, centerX, centerY); 29. }else{ 30. image2.setVisibility(View.GONE); 31. image1.setVisibility(View.VISIBLE); 32. image1.requestFocus(); 33. 34. rotation =newFlip3dAnimation(90,0, centerX, centerY); 35. } 36. 37. rotation.setDuration(500); 38. rotation.setFillAfter(true); 39. rotation.setInterpolator(newDecelerateInterpolator()); 40. 41. if(mIsFirstView) { 42. image2.startAnimation(rotation); 43. }else{ 44. image1.startAnimation(rotation); 45. } 46. } 47. }
SwapViews does exactly what its name suggests and swaps the images, setting one image to invisible and the other to visible depending on which image was already visable, but it also does one last important thing, and that is to create and apply the last half of the animation.
You should now have a working flip animation. This technique can also be applied to ViewGroups , so it could be used as a way to transition between different views. There are a few more things that we can do to this animation to improve it such as adding a depth effect, but I'll leave that to another post. Like I mentioned earlier, this example is based on the samples that are in the downloadable SDK files, so have a look at these samples as well.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android中关于线程使用的几点注意事项
  2. Android(安卓)TextView实现滚动跑马灯效
  3. Android(安卓)Animation学习笔记
  4. Android(安卓)toolbar与actionbar区别
  5. Android层次化安全架构及核心组件概览
  6. 使用Android(安卓)adb命令来启动Android
  7. Android热修复技术链接收集
  8. Android(安卓)渗透测试学习手册 第二章
  9. 新书内容连载(3):Android(安卓)SDK中常用命
  10. 基于ANDROID的网上订餐系统