Android implements the ever-changing Viewpager toggle Animation _android

Source: Internet
Author: User
Tags abs object object

Previously wrote an article: Android custom Viewpager to achieve personalized picture switching effect, a friend proposed, Viewpager brought a setpagetransformer to set up a toggle animation ~
In this article, you will learn the following:
1, describes how to use Setpagetransformer settings to toggle animation;
2, the custom Pagetransformer realizes the individuality the switching animation;
3, the method in the SDK11 below the version does not work, we will make a certain change, so that its backward-compatible.
Official example Address: http://developer.android.com/training/animation/screen-slide.html interested can go to see ~ ~

OK, now start writing code ~ ~
first, the use of Setpagetransformer
first of all, we quickly realize a traditional viewpager effect ~
1. layout file

<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 " > 
 
  <android.support.v4.view.viewpager 
    android:id= "@+id/id_viewpager" 
    android:layout_width= " Fill_parent " 
    android:layout_height=" fill_parent "/> 
 
</RelativeLayout> 

2, mainactivity

Package Com.zhy.demo_zhy_08_viewpageranim; 
Import java.util.ArrayList; 
 
Import java.util.List; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.support.v4.view.PagerAdapter; 
Import Android.support.v4.view.ViewPager; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
Import Android.view.Window; 
Import Android.widget.ImageView; 
 
Import Android.widget.ImageView.ScaleType; 
  public class Mainactivity extends activity {private Viewpager Mviewpager; 
  Private int[] Mimgids = new int[] {r.drawable.guide_image1, r.drawable.guide_image2, r.drawable.guide_image3}; 
 
  Private list<imageview> mimageviews = new arraylist<imageview> (); 
 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Requestwindowfeature (Window.feature_no_title); 
 
    Setcontentview (R.layout.activity_main); 
 
    InitData (); 
 
Mviewpager = (Viewpager) Findviewbyid (R.id.id_viewpager);    Mviewpager.setadapter (New Pageradapter () {@Override public Object instantiateitem (ViewGroup contai 
        NER, int position) {Container.addview (Mimageviews.get (position)); 
      return Mimageviews.get (position); 
 
        @Override public void Destroyitem (ViewGroup container, int position, object object) { 
      Container.removeview (Mimageviews.get (position)); @Override public boolean isviewfromobject (view view, Object object) {return View = = obj 
      ect 
      @Override public int GetCount () {return mimgids.length; 
 
  } 
    }); private void InitData () {for (int imgid:mimgids) {ImageView ImageView = new ImageView (Getap 
      Plicationcontext ()); 
      Imageview.setscaletype (Scaletype.center_crop); 
      Imageview.setimageresource (Imgid); 
    Mimageviews.add (ImageView); 
 } 
  } 
 
}

Well, such a traditional viewpager is realized ~ ~ Everyone on the above code should not have any strange feeling ~ running effect also do not need to map, we must know.

Second, Pagetransformer
Viewpager has a method called:
Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) is used to set the animation effect of the Viewpager switch, And Google officially gave two examples.
You only need to call Setpagetransformer in the above code to add toggle animation effect ~ ~ Below is a demo of Google's two Pagetransformer code and how it works.
1), Depthpagetransformer

public class Depthpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.75f; 
 
    public void Transformpage (view view, float position) {int pagewidth = View.getwidth (); 
      if (Position <-1) {//[-infinity,-1)//This page was way off-screen to the left. 
 
    View.setalpha (0); else if (position <= 0) {//[ -1,0]//Use the default slide transition when moving to the left page VI 
      Ew.setalpha (1); 
      View.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 transition View.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 way off-screen to the right. 
    View.setalpha (0); 
 } 
  } 
}

Calling code:
Mviewpager.setpagetransformer (True, New Depthpagetransformer ());
Effect:

2), Zoomoutpagetransformer

Package Com.zhy.view; 
Import Android.annotation.SuppressLint; 
Import Android.support.v4.view.ViewPager; 
Import Android.util.Log; 
 
Import Android.view.View; public class Zoomoutpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.85 
  F 
 
  Private static final float Min_alpha = 0.5f;  
    @SuppressLint ("Newapi") public void transformpage (view view, float position) {int pagewidth = View.getwidth (); 
 
    int pageheight = View.getheight (); 
 
    LOG.E ("TAG", View + "," + Position + ""); 
      if (Position <-1) {//[-infinity,-1)//This page was way off-screen to the left. 
 
    View.setalpha (0); else if (position <= 1)//a page slide to page b; page A from 0.0-1 B page 1 ~ 0.0 {//[ -1,1]//Modify the default slide transi 
      tion to shrink the page as ok float scalefactor = Math.max (Min_scale, 1-math.abs (position)); 
      float Vertmargin = PageHeight * (1-scalefactor)/2; Float HORZMArgin = PageWidth * (1-scalefactor)/2; 
      if (Position < 0) {View.settranslationx (HORZMARGIN-VERTMARGIN/2); 
      else {View.settranslationx (-horzmargin + VERTMARGIN/2); 
      }//Scale the PAGE down (between Min_scale and 1) view.setscalex (scalefactor); 
 
      View.setscaley (Scalefactor); 
      Fade the page relative to its size. 
 
    View.setalpha (Min_alpha + (Scalefactor-min_scale)/(1-min_scale) * (1-min_alpha)); 
      else {//(1,+infinity]//This page was way off-screen to the right. 
    View.setalpha (0); 
 } 
  } 
}

Calling code:
Mviewpager.setpagetransformer (True, New Zoomoutpagetransformer ());
Effect:

The effect of the map are Google official online, our test map will be compatible with 3.0 of the following posted out, or repeat the ~ ~
Adding a switch for Viewpager is not very happy for a line of code, but it is incompatible with the version below 3.0, which is written on the annotation on the method:
Setting a Pagetransformer prior to Android 3.0 (API one) will have no effect before 3.0 version of this method is not effective, then let's look at how to make it compatible with the following version 3.0.
third, the version of Backward compatibility
1), incompatible reasons
First look at why incompatible, 3.0 below it?
Looking at the two sample code above, the view animation in the code uses the property animation, and the property animation is 3.0 before the launch, so it must be incompatible with 3.0 below.
So we first introduce nineoldandroids, so that the animation can run under 3.0 to say:
Modify Depthpagetransformer

Package Com.zhy.view; 
 
Import Com.nineoldandroids.view.ViewHelper; 
Import Android.annotation.SuppressLint; 
Import Android.support.v4.view.ViewPager; 
 
Import Android.view.View;  
 
  public class Depthpagetransformer implements Viewpager.pagetransformer {private static final float Min_scale = 0.75f; 
 
    public void Transformpage (view view, float position) {int pagewidth = View.getwidth (); 
      if (Position <-1) {//[-infinity,-1)//This page was way off-screen to the left. 
      View.setalpha (0); 
    Viewhelper.setalpha (view, 0); else if (position <= 0)//a page slide to B page, page A from 0.0-1 b page from 1 ~ 0.0 {//[ -1,0]//Use the default slide transitio 
      n when moving to the left page//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) {//(0,1]//Fade the page out. 
      View.setalpha (1-position); 
 
      Viewhelper.setalpha (view, 1-position); 
      CounterAct the default slide transition//View.settranslationx (PageWidth *-position); 
 
      Viewhelper.settranslationx (View, PageWidth *-position); 
      Scale the page down (between Min_scale and 1) Float scalefactor = Min_scale + (1-min_scale) * (1-position); 
      View.setscalex (Scalefactor); 
      Viewhelper.setscalex (view, scalefactor); 
      View.setscaley (1); 
 
    Viewhelper.setscaley (view, scalefactor); 
      else {//(1,+infinity]//This page was way off-screen to the right. 
      View.setalpha (0); 
    Viewhelper.setalpha (view, 1); 
 } 
  } 
}

Quite simply, it would be nice to replace all the attribute animations with Viewhelper. Now we go to 3.0 below the machine to run, found that there is no effect ~ ~ ~
Why, then?
Let's take a look at Setpagetransformer's source code:

public void Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) { 
    if (Build.VERSION.SDK_ INT >= one) { 
      final Boolean hastransformer = transformer!= null; 
      Final Boolean needspopulate = Hastransformer!= (mpagetransformer!= null); 
      Mpagetransformer = transformer; 
      Setchildrendrawingorderenabledcompat (Hastransformer); 
      if (hastransformer) { 
        Mdrawingorder = Reversedrawingorder? Draw_order_reverse:draw_order_forward; 
      } else { 
        mdrawingorder = Draw_order_default; 
      } 
      if (needspopulate) populate (); 
    } 
  } 

Finally found the reason, originally in this method internal judge if it is more than 11 version to let animation effective ~ ~
Then, no way, if you want to be compatible, you must modify the source code of the Viewpager ~ ~
2), Perfect backward compatibility
We will copy the source code of Viewpager to our project, modify the name of Viewpagercompat; then comment out the SDK version and judge the sentence.

public class Viewpagercompat extends ViewGroup {public
void Setpagetransformer (Boolean reversedrawingorder, Viewpager.pagetransformer transformer) { 
//    if (Build.VERSION.SDK_INT >=)  
    { 
      Final Boolean Hastransformer = transformer!= null; 
      Final Boolean needspopulate = Hastransformer!= (mpagetransformer!= null); 
      Mpagetransformer = transformer; 
      Setchildrendrawingorderenabledcompat (Hastransformer); 
      if (hastransformer) { 
        Mdrawingorder = Reversedrawingorder? Draw_order_reverse:draw_order_forward; 
      } else { 
        mdrawingorder = Draw_order_default; 
      } 
      if (needspopulate) populate (); 
    } 
  } 
...
}

Note that all the Pagetransformer use Viewpager.pagetransformer
Then we change the Viewpager in the project to Viewpagercompat; Remember to modify the layout file and Viewpager in mainactivity for Viewpagercompat
We tested the effect on the 2.3.3 simulator:


Can see, our switch animation perfect running in 2.3.3 machine ~~so Happy ~ ~ No Viewpager source of children's shoes do not matter, I will be in the end of the source code download add Viewpager source code, so you can enjoy to test ~ ~
Of course, only compatibility can not satisfy our curiosity, we have done compatible, but also can only use Google to give the example of animation ~ ~ Our strong innovation ~ ~ Below lead us to analyze Setpagetransformer method, and then design a personality animation switching effect
Four, the custom Pagetransformer realizes the individuality to switch the animation

Public interface Pagetransformer { 
    /** 
    * Apply a property transformation to the given page. 
    * 
    * @param page Apply The transformation to this page 
    * @param position position of page relative to the "current F" Ront-and-center 
    *         position of the pager. 0 is front and center. 1 are one full 
    *         page position to the Righ T, And-1 is one page position to the left. 
    * 
    /public void Transformpage (View page, float position); 
  } 

You can see that the interface has only one method, the first one is our view, the second is position~~
When we slide: will print out of course Viewpager live in each view and their position changes ~ ~ Note that every one, so do not recommend log position, or you will feel inexplicably output ~ ~
The value of the possibility of position is, in fact, from the official example of the comments can be seen:
[-infinity,-1] is no longer visible.
(1,+infinity] can't see it anymore.
[ -1,1]
Focus on [ -1,1] This range, the other two view has not seen the ~ ~

Suppose Viewpager now slides out B on page A, then:
The position change of page A is (0,-1)
The position change of page B is [1, 0]
Know that we slide when the position change ~ ~ then began to design our personality switching effect;
Official examples, there are changes in transparency, offset, scaling, we are prepared to a different, we change the angle, that is rotation;
The approximate effect is this:

Here we analyze the code:
We set the rotation center of view to:

Viewhelper.setpivotx (view, View.getmeasuredwidth () * 0.5f);
Viewhelper.setpivoty (view, View.getmeasuredheight ());

The

is still viewpager on page A and now slide B page
So page A should be 0 degrees to 20 degrees in the sliding process, b page should be offset from +20 to 0 degrees in the sliding process
combine
A page position change is (0,-1)
The position change of page B is [1, 0]
so the angle of rotation is: Mrot = (* position); Page a mrot:0, ~-20; b page mrot:20 ~ 0 ;
instantly feels so simple:
Full code:

Package Com.zhy.view; 
 
Import Com.nineoldandroids.view.ViewHelper; 
Import Android.annotation.SuppressLint; 
Import Android.support.v4.view.ViewPager; 
Import Android.util.Log; 
 
Import Android.view.View;  public class Rotatedownpagetransformer implements Viewpager.pagetransformer {private static final float Rot_max = 
  20.0f; 
   
 
   
  private float Mrot; 
 
    public void Transformpage (view view, float position) {LOG.E ("TAG", View + "," + Position + ""); 
      if (Position <-1) {//[-infinity,-1)//This page was way off-screen to the left. 
 
    Viewhelper.setrotation (view, 0); else if (position <= 1)//a page slide to B page, page A from 0.0 ~-1; b page from 1 ~ 0.0 {//[ -1,1]//Modify the default slide tra 
        Nsition to shrink the page as OK if (position < 0) {Mrot = (Rot_max * position); 
        Viewhelper.setpivotx (view, View.getmeasuredwidth () * 0.5f); Viewhelper.setpivoty (View, View.getmeasuredheight()); 
      Viewhelper.setrotation (view, Mrot); 
        else {Mrot = (Rot_max * position); 
        Viewhelper.setpivotx (view, View.getmeasuredwidth () * 0.5f); 
        Viewhelper.setpivoty (view, View.getmeasuredheight ()); 
      Viewhelper.setrotation (view, Mrot); 
 
    }//Scale the PAGE down (between Min_scale and 1)//Fade the page relative to its size. 
      else {//(1,+infinity]//This page was way off-screen to the right. 
    Viewhelper.setrotation (view, 0); 
 } 
  } 
}

You are not mistaken, if else inside the code is the same, in order to better understand deliberately did not merge together.

To this end, we use from Setpagetransformer, to modify the Viewpager to do backward, until we define the personality of the switching effect has been introduced. Everyone can play their own creativity, make a variety of magical animation effect, OK, here!
If you like customizing Viewpager to implement, please move: Android custom Viewpager to achieve personalized picture switching effect
SOURCE Download: Viewpager Toggle Animation
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.