Android custom Viewpager to achieve personalized picture switching effect _android

Source: Internet
Author: User
Tags object object

The first time to see Viewpager this control, instantly fondle admiringly, do things the main interface all Viewpager, as well as the picture switch also abandoned imageswitch and so on, began to let Viewpager to do. Long time, viewpager switch effect feel boring, formed the aesthetic fatigue ~ ~ We need to change, today to teach you how to change the effect of Viewpager switch, the realization of personalized picture switching

Take a look at the picture switch for this effect:

is not more than the traditional effect of a lot of personality, hehe ~ ~ is actually very simple, learning to finish this article, to ensure that you can customize the switch effect, make a variety of effects.
1, before making the analysis
Observation of the effect of the picture, the actual change is the switch animation, so simple, only need the user in the switch, get the current view and the next view, and then add animation is not on it.

The first step is to get the current view of the user switching and the destination view to switch to.
We're going to look at the current view and destination view, we need to change the animation slowly, preferably according to the user's gestures to slide. For example, the above effect, the user sliding, the purpose of the picture according to the user sliding distance slowly appear and become larger.

The second step is to design the gradient variation of the animation.

After analysis, we summed up two steps, below we start step-by-step to create ever-changing picture switching effect

2, get the user to switch the current view and switch to the destination view. Viewpager also needs to listen to the user's gestures, so it definitely provides a way. So looking at the Viewpager method, we found a method called onpagescrolled (int position, float positionoffset, int positionoffsetpixels).
Yes, that's the way it is: call when the page scrolls
Take a closer look at the following parameters:
Say the test results directly:
When not on the first and last page, slide to the next page, position to the current page position; slide to previous page: position for current page-1
Positionoffset sliding to the next page, [0,1] interval changes; sliding to previous page: (1,0] Change on the interval
Positionoffsetpixels This is similar to the Positionoffset: sliding to the next page, [0, Width] range changes; sliding to previous page: (width, 0] range changes
First page: Slide to previous page position=0, other basic 0; the last page slides to the next page position is the current page position, and the other two parameters are 0

Suddenly found that we need the steps of the second step to solve, positionoffset very suitable as a gradient, zoom control parameters, Positionoffsetpixels can be used as a translation of control parameters.
So how do you get the current view and destination view:
share a few of my misguided:
1, "Error"I passed Getchildat (position), Getchildat (position+1), Getchildat (position-1) to get a slide when the left and right two view; At first glance, it really feels good ~ ~ ~ in the code written out, Then the effect also does not come out ~ ~ Wrong reason: We ignore a particularly big thing, viewpager mechanism, sliding dynamic loading and delete View,viewpager In fact will only maintain 2 to 3 view, and the scope of position is basically unlimited ~ ~
2, "error"I get the current position through Getcurrentitem, and then +1,-1 to get the next one or a ~ ~ is stealing hi, quickly code changed, the effect is not right, a mess ~ ~ Carefully observe the log, this getcurrentitem when the user finger left the screen, Page also in animation implementation, it changed ~ ~ No wonder ~ the whole sliding process is not fixed ~ ~ Alas, the heart is broken ~
3, "error"Position is unchanged throughout the slide, and Viewpager will hold 2 or 3 view; then I think, if it's 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 right, so I encountered the first issue, the first page, regardless of the left and right position are 0, ni, which is left view, Which is right view~~
Said so many mistakes, we can bypass these detours, but also from these detours inside see something ~
The right thing to say is, in fact, when Viewpager adds a view or destroys a view, it is controlled by our own pageadapter, so we can maintain a hashmap<position,view in Viewpager Then, when sliding, through get (position) out, such as the above effect, is always the right view changes, or from small to large, or from large to small
Soslide down one page:View:map.get (position) on the left, View:map.get on the right (position+1).
SoSlide the previous page down:View:map.get on the left (position), View:map.get on the right (position+1), the same, because 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"; 
 Private int[] Mimgids; 
 
 Private Myjazzyviewpager Mviewpager; 
 @Override protected 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 () {@Override public boolean isviewfromobject (View arg0, Object arg1) 
  {return arg0 = = Arg1; @Override public void Destroyitem (ViewGroup container), inT position, object) {Container.removeview ((View) object); @Override public Object Instantiateitem (viewgroup container, int position) {ImageView ImageView = new Ima 
  Geview (Mainactivity.this); 
  Imageview.setimageresource (Mimgids[position]); 
  Imageview.setscaletype (Scaletype.center_crop); 
  Container.addview (ImageView); 
  Mviewpager.setobjectforposition (ImageView, position); 
  return ImageView; 
  @Override public int GetCount () {return mimgids.length; 
 
 } 
 }); 
 } 
 
}

This very common code, 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, to give our map stored value
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; 
 /** * The largest reduction ratio * * Private static final float Scale_max = 0.5f; 
 private static final String TAG = "Myjazzyviewpager"; /** * Save position and for view * * Private Hashmap<integer, view> mchildrenviews = new Linkedhashmap<integer, view 
 > (); 
 /** * The element on the left when sliding * * * private View mleft; 
 
 /** * The element on the right when sliding * * * private View mright; 
 Public Myjazzyviewpager (context, AttributeSet attrs) {Super (context, attrs); @Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {//Lo G.E (TAG, "Position= "+ position+", Positionoffset = "+positionoffset+", Positionoffsetpixels = "+ positionoffsetpixels+", CurrentPos 
  
 = "+ Getcurrentitem ()); Sliding particularly small distances when we think there is no moving, dispensable judgment float Effectoffset = Issmall (positionoffset)? 
  
 0:positionoffset; 
 Gets the View Mleft = Findviewfromobject (position) on the left; 
  
 Get View Mright = Findviewfromobject on the right (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); 
 /** * Access to the corresponding view * * @param position * @return/public view findviewfromobject (int position) { 
 return Mchildrenviews.get (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) {/** * Zoom out if the finger slides from starboard to left (switch to the latter): 0.0~1.0, that is, from half to maximum * If the fingers slide from left to right (switch to the previous one): 1.0~0, that is, from maximum to 
  Half * * Mscale = (1-scale_max) * effectoffset + Scale_max; /** * x offset: If the finger slides from right to left (switch to the latter): 0-720 If the fingers slide from left to right (switch to the previous one): 720-0 * * Mtrans =-getwidth ()-getpagemargin () + posit 
  Ionoffsetpixels; 
  Viewhelper.setscalex (right, Mscale); 
  Viewhelper.setscaley (right, Mscale); 
 Viewhelper.settranslationx (right, Mtrans); 
 } if (left!= null) {Left.bringtofront (); 
 } 
 } 
}

You can see that the core code is onpagescrolled, we passed findviewfromobject (position); Findviewfromobject (position + 1), get the left and right view, and then add animation effect; This example now adds two animations, One is to zoom out from 0.5 to 1.0 or 1.0 to 0.5, yes by our positionoffset to provide gradient changes ~ ~ There is a translation of the animation: the next page directly to the current screen (the default is on the right, you can annotate this effect, how to run the look), Then continuously through Positionoffsetpixels offset the original default movement of the displacement, so that users feel it in situ zoom in to reduce ~ ~
Well, this is achieved ~ ~ You can write your favorite animation effects, such as the default above add 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, Jazzyviewpager use
in fact, the above implementation is GitHub on the Jazzyviewpager source code, use Needless to say, is our mainactivity, It has a built-in 10来 effect, we can set the animation effect through the code or layout ~ ~ We above the example effect, it is called stack;
use Jazzviewpager code: In fact, basically the same ~ ~ Finally will be posted on 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"; 
 Private int[] Mimgids; 
 
 Private Jazzyviewpager Mviewpager; 
 @Override protected 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 () {@Override public boolean isviewfromobject (View arG0, Object arg1) {return arg0 = = Arg1; @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.remove 
  View (view) object); @Override public Object Instantiateitem (viewgroup container, int position) {ImageView ImageView = new Ima 
  Geview (Mainactivity.this); 
  Imageview.setimageresource (Mimgids[position]); 
  Imageview.setscaletype (Scaletype.center_crop); 
  Container.addview (ImageView); 
  Mviewpager.setobjectforposition (ImageView, position); 
  return ImageView; 
  @Override public int GetCount () {return mimgids.length; 
 
 } 
 }); 
 } 
 
}

The only difference from our code is this:
//Set Toggle Effect
Mviewpager.settransitioneffect (Transitioneffect.stack);
It has 12 kinds of optional switching effect, in fact, is to write a 12 switch animation ~ ~ ~
Well, finally, attach a effect that I prefer: a Tablet

SOURCE download: Viewpager picture switching

This is the entire content of this article, I hope to learn more about Android software programming help.

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.