Android Custom Viewpager to create ever-changing image transitions

Source: Internet
Author: User
Tags switches

Reprint please indicate source:http://blog.csdn.net/lmj623565791/article/details/38026503

Remember the first time to see Viewpager this control, instantly put it down, do things the main interface all Viewpager, as well as the picture switch also abandoned imageswitch such as, began to let Viewpager to do. Long time, Viewpager switching effect felt boring, forming an aesthetic fatigue ~ ~ We need to change, today teach you how to change the effect of Viewpager switch, to achieve personalized picture switch ~ ~

Take a look at the image toggle for this effect:


is not more than the traditional effect of a lot of personality, hehe ~ ~ Actually very simple, study this blog, to ensure that you can customize the switch effect, to make a variety of insane switch ~ ~

1, pre-production analysis

Observation, in fact, the change is the animation of the switch, so simple, just need the user in the switch, get the current view and the next view, and then add animation is not right. OK, the first step is to get the current view and switch to the destination view when the user switches.

We are looking at, if the current view and destination view, for the animation we need a slow change, preferably based on the user's gesture swipe. For example, the above effect, the user sliding, the purpose of the image according to user sliding distance slowly appear and slowly become larger. OK, step two, design the gradient of the animation.

After analysis, we summed up the two steps, below we begin to build a step-by-step to create ~ ~ ~

2. Get the current view and switch to the destination view when the user switches.

Viewpager also needs to listen to the user's gestures, so there is definitely a way to do it. So looking at the method of Viewpager, I found a method called onpagescrolled (int position, float positionoffset, int positionoffsetpixels) ~ ~

Yes, that's the way: called when the page scrolls

These parameters are carefully examined below:

Directly say the test results:

In the non-first and last page, swipe to the next page, position is the current page position; Swipe to previous: position current page-1

Positionoffset slide to the next page, [0,1] change on the interval; swipe to previous: (1,0] Change on interval

Positionoffsetpixels This is very much like the positionoffset: sliding to the next page, [0, Width] changes on the interval; slide to previous: (width, 0] change on interval

First page: Swipe to the previous page position=0, the other basic is 0; the last page slides to the next page position the current page position, the other two parameters are 0


Suddenly found that the second step of the steps we need to solve, positionoffset is well suited as a control parameter for gradients, scaling, and positionoffsetpixels can be used as a control parameter for panning.

So how do you get the current view and the destination view:

Share a few of my astray:

1, "error" I through Getchildat (position), Getchildat (position+1), Getchildat (position-1) Get sliding, about two view; At first glance, I really feel good. ~ ~ ~ In the code to write, and then the effect can not come ~ ~ Error Reason: We ignore a particularly large thing, viewpager mechanism, sliding dynamic loading and deletion of View,viewpager actually only maintain 2 to 3 view, and position's range is basically unlimited ~ ~

2, "error" I get the current position through the Getcurrentitem, and then +1,-1 get the latter one or the previous ~ ~ is stealing Hi, quickly code to change over, the effect is not right, messy ~ ~ Carefully observe the log, This getcurrentitem when the user finger left the screen, page also in the animation execution, it changed ~ ~ No wonder ~ the whole sliding process is not fixed ~ ~ Alas, the heart is broken ~

3, "error"position during the entire sliding process is not changed, and Viewpager will save 2 or 3 view; then I think, if it is the first page, or the last page then I take Getchildat (0) and Getchildat ( 1), if the other page is Getchildat (0), Getchildat (2), and then after a series of changes ~ I think this will always be the right, so I met the first question, the first page, regardless of the left and right position are 0, and, what is left view, Which is right view~~

Having said so many mistakes, we can get around these detours and see what is in these detours.

The following is true, in fact Viewpager in adding a view or destroy a view, is our own pageadapter control, so we can in Viewpager to maintain a hashmap<position,view , and then slide it out through get (position), such as the above effect, is always the right view change, either from small to large, or from big to small

Then slide down a page: View:map.get (position) on the left, View:map.get on the right (position+1).

So slide the previous page: View:map.get on the left (position), the right View:map.get (position+1), the same as the slide to the previous page, position for the current page-1

Well, so far, we've analyzed and solved all the steps.

3. Code

Mainactivity

Package Com.example.zhy_jazzyviewpager;import Android.app.activity;import Android.os.bundle;import Android.support.v4.view.pageradapter;import Android.view.menu;import Android.view.view;import Android.view.viewgroup;import Android.widget.imageview;import Android.widget.imageview.scaletype;public Class Mainactivity extends activity{protected static final String TAG = "mainactivity";p rivate int[] mimgids;private Myjazzyvie Wpager Mviewpager; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mimgids = new int[] {r.drawable.a, r.drawable.b, R.DRAWABLE.C,R.DRAWABLE.D}; Mviewpager = (Myjazzyviewpager) Findviewbyid (R.id.id_viewpager); Mviewpager.setadapter (new PagerAdapter () {@ Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic void Destroyitem (ViewGroup container, int position,object object) {Container.removeview (View) object) ;} @Overridepublic Object InstantiateitEM (viewgroup container, int position) {ImageView ImageView = new ImageView (mainactivity.this); Imageview.setimageresource (Mimgids[position]); Imageview.setscaletype (Scaletype.center_crop); Container.addView ( ImageView); Mviewpager.setobjectforposition (imageView, position); return ImageView;} @Overridepublic int GetCount () {return mimgids.length;}});}}

This very common code, that is, the initialization of viewpager~~ there is nothing to say ~ ~ One thing to note: In the Instantiateitem method, we call a mviewpager.setobjectforposition (ImageView , position); in fact, in order to save our map values

Mainly look at the custom Viewpager

Package Com.example.zhy_jazzyviewpager;import Java.util.hashmap;import Java.util.linkedhashmap;import Android.content.context;import Android.support.v4.view.viewpager;import Android.util.attributeset;import Android.util.log;import Android.view.view;import Com.nineoldandroids.view.viewhelper;public class MyJazzyViewPager Extends viewpager{private float mtrans;private float mscale;/** * Maximum reduced ratio */private static final float Scale_max = 0.5F;PR Ivate static final String TAG = "Myjazzyviewpager";/** * Save position with for View */private Hashmap<integer, view> Mchildr Enviews = new Linkedhashmap<integer, view> ();/** * Slide when left element */private view mleft;/** * Slide when right element */private view Mrigh T;public Myjazzyviewpager (Context context, AttributeSet Attrs) {Super (context, attrs);} @Overridepublic void onpagescrolled (int position, float positionoffset,int positionoffsetpixels) {//log.e (TAG, " position= "+ position+", Positionoffset = "+positionoffset+", Positionoffsetpixels = "+ positionoffsetpixels+",Currentpos = "+ Getcurrentitem ());//sliding particularly small distances, we think that there is no move, dispensable judgment float Effectoffset = Issmall (positionoffset)? 0:positionoffset;//Get left viewmleft = findviewfromobject (position);//Get Right viewmright = findviewfromobject (position + 1 );//Add Toggle Animation effect Animatestack (Mleft, Mright, Effectoffset, positionoffsetpixels); super.onpagescrolled (position, Positionoffset, positionoffsetpixels);} public void setobjectforposition (view view, int position) {Mchildrenviews.put (position, view);} /** * through location to get the corresponding View * * @param position * @return */public View findviewfromobject (int position) {return MCHILDRENVIEWS.G ET (position);} Private Boolean Issmall (float positionoffset) {return Math.Abs (Positionoffset) < 0.0001;} protected void Animatestack (view left, view right, float Effectoffset,int positionoffsetpixels) {if (right! = null) {/** * indent Small proportions if the fingers are sliding from right to left (switch to the latter one): 0.0~1.0, that is, from half to maximum * if the fingers are sliding from left to right (switch to the previous one): 1.0~0, i.e. from maximum to half */mscale = (1-scale_max) * Effectoffset + SC ale_max;/** * x offset: If your finger is sliding from right to left (switch to the latter): 0-720 if your finger slips from left to right (switch toPrevious): 720-0 */mtrans =-getwidth ()-getpagemargin () + positionoffsetpixels; Viewhelper.setscalex (right, Mscale); Viewhelper.setscaley (right, Mscale); Viewhelper.settranslationx (right, Mtrans);} if (left! = null) {Left.bringtofront ();}}}

As you can see, the core code is onpagescrolled, we pass findviewfromobject (position); Findviewfromobject (position + 1), respectively get the left and right side of the view, and then add animation effect; The current example adds two animations, One is to zoom in from 0.5 to 1.0 or 1.0 to 0.5, yes by our Positionoffset provide gradient change ~ ~ There is also a translation animation: The next page is moved directly to the current screen (the default is on the right, you can annotate the effect, how to run a look), Then constantly through the positionoffsetpixels to offset the original default movement of the displacement, so that users feel it in situ zoom in and out ~ ~

OK, so it is realized ~ ~ You can write your favorite animation effects, such as the default above the addition of a fade or God horse, casually ~ ~ is not very casual ~ ~

Our layout files:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "  >    <com.example.zhy_jazzyviewpager. Myjazzyviewpager        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android: Id= "@+id/id_viewpager"/></relativelayout>


4, the use of Jazzyviewpager

In fact, the above implementation is GitHub on the Jazzyviewpager source, usage Needless to say, is our mainactivity, it built up the approximate 10来 kind of effect, we can set the animation effect through the code or layout above ~ ~ Our above example effect, It's called a stack;

Use Jazzviewpager code: In fact, basically the same ~ ~ finally will be affixed to the Jazzyviewpager source of the download

Mainactivity

Package Com.jfeinstein.jazzyviewpager;import Com.jfeinstein.jazzyviewpager.JazzyViewPager.TransitionEffect; Import Android.app.activity;import Android.os.bundle;import Android.support.v4.view.pageradapter;import Android.view.view;import Android.view.viewgroup;import Android.widget.imageview;import Android.widget.imageview.scaletype;public class Mainactivity extends activity{protected static final String TAG = " Mainactivity ";p rivate int[] mimgids;private jazzyviewpager mviewpager; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mImgIds = new int[] {r.drawable.a, r.drawable.b, R.DRAWABLE.C,R.DRAWABLE.D};mviewpager = (jazzyviewpager) findViewById (R.id.id_ Viewpager);//Set Switch effect Mviewpager.settransitioneffect (transitioneffect.stack); Mviewpager.setadapter (new Pageradapter () {@Overridepublic Boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic void Destroyitem (ViewGroup container, int Position,object object) {Container.removeview (View) object);} @Overridepublic Object Instantiateitem (viewgroup container, int position) {ImageView ImageView = new ImageView ( Mainactivity.this); Imageview.setimageresource (Mimgids[position]); Imageview.setscaletype (ScaleType.CENTER_CROP) ; Container.addview (ImageView); Mviewpager.setobjectforposition (imageView, position); return ImageView;} @Overridepublic int GetCount () {return mimgids.length;}});}}

The only difference from our code is:

Set the toggle Effect
Mviewpager.settransitioneffect (Transitioneffect.stack);

It has 12 of the optional switching effect, in fact, is to write 12 transitions animation ~ ~ ~

Well, I'll end up with an effect I like better: the Tablet


Finally, like to take this blog to ask ~ ~ Everyone on the github of interest on the code, can be analyzed and their own attempt to achieve, sometimes will find it is not difficult ~ You can also do!


SOURCE Click to download





Android Custom Viewpager to create ever-changing image transitions

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.