Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/44200623
Viewpager is one of the most commonly used components of Android and is believed to be frequently used in projects, such as the use of Viewpager to make guide pages, Carousel diagrams, and even the framework of the entire app's presentation layer.
Switching animations is not supported under Android3.0
However, the Android 3.0 (API 11) below the Viewpager is relatively inflexible, does not support animation effects, which also let Viewpager in the time of the switch can not achieve a good user experience, Here is the implementation code for the Viewpager with no animations below Android3.0 and the effect demo:
public class Mainactivity extends Activity {private Viewpager mviewpager;private int[] imgres = new int[] {R.drawable.gui De_image1, R.drawable.guide_image2, r.drawable.guide_image3};p rivate list<imageview> imgList = new ArrayList <ImageView> (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate ); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_main); MViewPager = (ViewPager) Findviewbyid (R.id.viewpager); Mviewpager.setadapter (new Pageradapter () {@Overridepublic Boolean isviewfromobject ( View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic int GetCount () {return imgres.length;} @Overridepublic Object Instantiateitem (viewgroup container, int position) {ImageView Mimageview = new ImageView ( Mainactivity.this); Mimageview.setbackgroundresource (Imgres[position]); Mimageview.setscaletype (ScaleType.CENTER _crop); Imglist.add (Mimageview); Container.addview (Mimageview); return mimageview;} @Overridepublic void deStroyitem (ViewGroup container, int position, object object) {Container.removeview (imglist.get);}});}}
The above is the simplest viewpager to use the demo, run as follows, looks very ordinary very rigid:
Official method to support Android3.0 more fortunately, Google has added an API to the Viewpager settings toggle Animation in the Android3.0 version above, allowing developers to add animation transitions to Viewpager in more than Android3.0 versions of the app, so you can Let the viewpager switch effect becomes more brilliant, the API to add animation effects for Viewpager is as follows:
public void Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) {...}
Where the first parameter, the Boolean type, is set to True, the second parameter, Pagetransformer, is our custom animation effect:
Mviewpager = (Viewpager) Findviewbyid (R.id.viewpager); Mviewpager.setpagetransformer (True, new Zoomoutpagetransformer ());
The Zoomoutpagetransformer code is from Google's training document, the English good friend can go directly to the document view, the link is
http://developer.android.com/training/animation/screen-slide.htmlThe source code is as follows:
public class Zoomoutpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.85F;PR Ivate static final float Min_alpha = 0.5f;public void Transformpage (view view, float position) {int pagewidth = View.getwi DTH (); int pageheight = View.getheight (); if (position <-1) {//[-infinity,-1]//This page is the off-screen T.view.setalpha (0);} else if (position <= 1) {//[ -1,1]//Modify the default slide transition to shrink the page as wellfloat scalefactor = Math.max (Min_scale, 1-math.abs (position)); float Vertmargin = PageHeight * (1-scalefactor)/2;float horzmargin = page Width * (1-scalefactor)/2;if (Position < 0) {View.settranslationx (HORZMARGIN-VERTMARGIN/2);} else {View.settran Slationx (-horzmargin + VERTMARGIN/2);} Scale the PAGE down (between Min_scale and 1) view.setscalex (scalefactor); View.setscaley (scalefactor);//Fade the page R Elative to its Size.view.setAlpha (Min_alpha + (Scalefactor-min_scale)/(1-min_scaLE) * (1-min_alpha));} else {//(1,+infinity]//This page was the off-screen to the Right.view.setAlpha (0);}}
In addition to the Google document also provides a way to implement another animation, I will temporarily attach the source code below:
public class Depthpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.75f;publ IC void Transformpage (view view, float position) {int pagewidth = View.getwidth (); if (position <-1) {//[-infinity,-1 )//This page is the-off-screen to the Left.view.setAlpha (0);} else if (position <= 0) {//[ -1,0]//Use the default slide transition when moving to the left pageview.setalpha (1); Vie W.settranslationx (0); View.setscalex (1); View.setscaley (1);} else if (position <= 1) {//(0,1]//Fade the page out.view.setAlpha (1-position);//counteract the default slide tran Sitionview.settranslationx (PageWidth *-position);//Scale the PAGE down (between Min_scale and 1) float scalefactor = Min_ Scale + (1-min_scale) * (1-math.abs (position)); View.setscalex (scalefactor); View.setscaley (scalefactor);} else {//(1,+infinity]//This page was the off-screen to the Right.view.setAlpha (0);}}
The effect of the two methods is as follows, one is Zoomoutpagetransformer, the other is Depthpagetransformer
Compatible with Android3.0 the following version of the earlier we said, Android3.0 the following version is not supported Viewpager to increase the switching animation, the reason is very simple, we can refer to the above posted two code, you can see the two pieces of code are used in the Android properties of the animation write switching effect, we know Android Property Animation is a feature that comes out of Android3.0, only supports Android3.0 and above, so Viewpager switching animations are not supported in the Android3.0 versions below. After analyzing the reasons why we cannot add animations to the following versions of Android3.0, we can solve this compatibility problem by other means. Remember before we talked about a foreigner in the blog of a Daniel--jakewharton, right, this Daniel in GitHub open source for Android3.0 the following system to add Property animation project--nineoldandroids, We can download the source code or the jar to import into our project, use it to be compatible with our Android3.0 version below. Jakewharton's homepage is:
Https://github.com/JakeWhartonNineoldandroids's homepage is:
Https://github.com/JakeWharton/NineOldAndroidsHere's what I did after I changed the view in the Depthpagetransformer class to Viewhelper under Nineoldandroids, and modified the property animations that are compatible with the Android3.0 versions below:
public class Depthpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.75f;publ IC void Transformpage (view view, float position) {int pagewidth = View.getwidth (), if (position <-1) {//View.setalpha ( 0); Viewhelper.setalpha (view, 0);} else if (position <= 0) {//View.setalpha (1); Viewhelper.setalpha (view, 1);//View.settranslationx (0); Viewhelper.settranslationx (view, 0);//View.setscalex (1); Viewhelper.setscalex (view, 1);//View.setscaley (1); Viewhelper.setscaley (view, 1);} else if (position <= 1) {//View.setalpha (1-position); Viewhelper.setalpha (view, 1-position);//View.settranslationx (PageWidth *-position); Viewhelper.settranslationx (View, PageWidth *-position); float scalefactor = Min_scale + (1-min_scale) * (1-math.abs (PO sition));//View.setscalex (scalefactor); Viewhelper.setscalex (view, scalefactor);//View.setscaley (scalefactor); Viewhelper.setscaley (view, scalefactor);} else {//View.setalpha (0); Viewhelper.setalpha (view, 0);}}
In order to understand, I did not delete the source code provided by Google, but commented out, convenient for everyone to compare reading, however, even if the use of Nineoldandroids to our animation source code has been modified, When we open a Android2.3 simulator to run the time to find that there is no effect, that is, the animation effect is not executed, in the emulator running the Viewpager slide effect is the original default left and right to switch the animation, this is how it? So far, we need to open Viewpager source for reading, since it is in Mviewpager.setpagetransformer (true, New Depthpagetransformer ()), this code does not play an effect, Then we'll just go in and check out the source code of Setpagetransformer This method, the source code is as follows:
public void Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) {if (Build.VERSION.SDK_INT >= {Boolean Hastransformer = transformer! = Null;boolean Needspopulate = hastransformer! = (This.mpagetransformer!) = null); This.mpagetransformer = Transformer;setchildrendrawingorderenabledcompat (Hastransformer); if ( Hastransformer) {This.mdrawingorder = (reversedrawingorder? 2:1);} else {this.mdrawingorder = 0;} if (needspopulate) populate ();}}
Well, the source at a glance, we analyzed in Viewpager in the Setpagetransformer this method, first judged the current device build.version_sdk_int>= 11, that is, the current device is Android3.0 above the system, the method body execution no problem, but if 3.0, then sorry, unable to execute. Know this reason after we need to solve this problem, I changed a bit here Viewpager source, modify the source code of Viewpager, readers can first download a copy of the Viewpager source, and then copy to the project, rename it, The IF judgment statement inside is deleted. Here is my revised part of the source code, named Viewpagercompat:
public void Setpagetransformer (Boolean reversedrawingorder, Viewpager.pagetransformer transformer) {//if ( Build.VERSION.SDK_INT >=) {Final Boolean hastransformer = transformer! = null;final Boolean needspopulate = Hastrans Former! = (Mpagetransformer! = null); Mpagetransformer = Transformer;setchildrendrawingorderenabledcompat ( Hastransformer); if (hastransformer) {Mdrawingorder = Reversedrawingorder? Draw_order_reverse:draw_order_forward;} else {mdrawingorder = Draw_order_default;} if (needspopulate) populate ();/}}
Good, the source code is modified, the Viewpager in your source code is replaced with the modified source code Viewpagercompat, then the effect of Viewpager switch animation appears.
Analyze the animation source code, achieve their own animation effect above the animation source is I found in Google's official documents, the complete implementation of a series of animation functions. Then we can also through the analysis of the source code in Google Docs, find the rules, we do a self-implementation of their own animation effect? First take a look at Depthpagetransformer.java this section of the source code, this class implemented an interface Viewpager.pagetransformer, rewrite one of the methods
public void Transformpage (view view, float position) {... LOG.I ("TAG", "view =" + View + ", Position =" + position); ...}
As shown above, I'll first print out the values of the parameter view object and the position in this method, and then we'll look at the log output: Well, let's look at the log output logs and see that there are 2 view objects in the interlaced output, Where the hash value of the view that I checked is 4054c260, the hash value of the view with the unchecked callout is 4054c548, and then look at the value of position, it is important to note that 4054c260 view of the position value from 0.0 has been reduced to -1.0,4054c548 view of the position value from 1.0 has been reduced to 0.0, we for convenience, remember the hash value of 4054c260 view is a page, the hash value is 4054c548 View is page B. Scenario analysis, please also look at the source of Depthpagetransformer.java, when position < 1, at this time position does not represent the location of page A and page B, so here we do not do any animation out. When the position <= 0, the position range is between 0.0 ~-1.0, it can be thought to represent a page motion trajectory, that is, a page out of the screen. When position <= 1, at this time the range of position is between 1.0 ~ 0.0, it can be thought to represent the motion trajectory of page B, that is, page B is moved to the screen. When position > 1, at this time position does not represent the position of page A and page B, so here we do not do any animation out.
Well, through our analysis, we can realize that the animation effect is set according to the change of position. Well, now we're going to make a viewpager animation of ourselves based on position, and we'll do a viewpager spin out of the screen and spin the effect on the screen. The sketches are as follows:
Looking at the sketch, we imagine that when the finger is sliding to the left, page A will rotate a certain angle to move out of the screen, B will rotate a certain angle to the screen, then we will first set a constant angle of movement, here I assume the maximum rotation angle is 20 degrees, the following is my source:
/** * Viewpager Custom Rotation Animation * * @author Vincent * */public class Rotatedowntransformer implements Pagetransformer {//rotation max angle 20 degrees private static final float max_rotate = 20.0f;//angle in the rotation process private float currentrotate; @Overridepublic void Transformpa GE (view view, float position) {int pagewidth = View.getwidth (); LOG.I ("TAG", "view =" + View + ", Position =" + position), if (position <-1) {viewhelper.setrotation (view, 0);} else if (position <= 0) {//position range [ -1.0,0.0], at which point A-page animation moves out of the screen currentrotate = position * max_rotate;//Sets the rotation center point of the current page, the horizontal axis is the screen Width of 1/2, ordinate for screen height viewhelper.setpivotx (view, PAGEWIDTH/2); Viewhelper.setpivoty (view, View.getheight ()); Viewhelper.setrotation (view, currentrotate);} else if (position <= 1) {//Position range (0.0,1.0], at which point the B-page animation moves to the screen currentrotate = position * max_rotate;//Sets the rotation center point of the current page, the horizontal axis is the screen width Degree of 1/2, the ordinate is the height of the screen viewhelper.setpivotx (view, PAGEWIDTH/2); Viewhelper.setpivoty (view, View.getheight ()); Viewhelper.setrotation (view, currentrotate);} else {viewhelper.setrotation (view, 0);}}}
It's on the top. Oh, it seems to be OK, according to the above description, as long as you know the property animation related APIs, you can also customize the beginning of a variety of animation effects out, you can mix a variety of single animation effects together, so that the viewpager sliding effect looks more "complex."
Thanks to CSDN Blog expertHon YangSelfless dedication of tutorials, tutorials video address: http://www.imooc.com/learn/226
please download the source code here
Android adds toggle animations for Viewpager--using property animations