Android Curious baby _07_viewpager Toggle Animation (compatible with low version)

Source: Internet
Author: User
Tags call back

Idle Bored, write demo

Want to write a picture of the carousel, Baidu a bit basic is to achieve with Viewpager, then use Viewpager to practiced hand.

After writing the custom switch effect, found that 3.0 or less incompatible, had to think of ways.

First on:


Here's one step at a step:


(1) Write layout:

<            Relativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" > <jjj.demo.viewpagerdemo.animviewpager android:id= "@+id/test_viewpager" android:layout            _width= "Match_parent" android:layout_height= "300DP" android:background= "#f7f7f7" > </jjj.demo.viewpagerdemo.AnimViewPager> <jjj.demo.viewpagerdemo.diandian android:i D= "@+id/test_diandian" android:layout_width= "wrap_content" android:layout_height= "Wrap_conte                NT "android:layout_alignparenttop=" true "android:layout_centerhorizontal=" true "        android:layout_margintop= "270DP" app:count= "5" > </jjj.demo.viewpagerdemo.DianDian> </relativelayout> 

Animviewpager is my rewrite of the Viewpager, to solve the low version Viewpager does not support custom switch animation, here first as a normal viewpager on the line.

Diandian was a custom control I wrote a long time ago, which is the bottom 5 points.

Simple principle:

Diandian inherited the LinearLayout, by gradientdrawable this class to generate the selected and unselected points of the drawable, through the margin control interval distance, and then add to the linearlayout inside the line.


(2) Fill in the content for Viewpager:

Viewpager = (Animviewpager) Findviewbyid (R.id.test_viewpager); Initiamgelist (); Viewpager.setadapter (MAdapter);
initimagelist () Initializes a arraylist<imageview> of length 5 for testing purposes.

Madapter with other demos on the Web, nothing Special:

Pageradapter madapter = new Pageradapter () {public void Destroyitem (Android.view.ViewGroup container, int position, OBJEC T object) {((Animviewpager) container). Removeview (Imageviewslist.get (position));}; Public Object Instantiateitem (android.view.ViewGroup container, int position) {((Animviewpager) container). AddView ( Imageviewslist.get (position)); return imageviewslist.get (position);}; @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0.equals (arg1);} @Overridepublic int GetCount () {return 5;}};


(3) Setting monitoring

Set the pager toggle listener to toggle the display of the bottom 5 points.

Onpagechangelistener Mchangelistener = new Onpagechangelistener () {@Overridepublic void onpageselected (int arg0) { Diandian.setselect (arg0);} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpagescrollstatechanged (int a rg0) {}};

Well, I only wrote one sentence Diandian.setselect (arg0).


(4) Custom Toggle Animation

The above three steps are done after the Viewpager has been able to use the normal.

But we also wanted to do something cool, so we decided to customize the Viewpager of the switch animation effect.

So Baidu a bit, found that Google provides a simple way to achieve:

Viewpager.setpagetransformer (False, new Pagetransformer () {@Overridepublic void Transformpage (view view, float Position) {}});


The first parameter we don't care about (as if it's the drawing order), the second argument is the Pagetransformer type.


In fact, this is the same as setting up the monitoring, as we often write:

Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {}});

Viewpager corresponds to button,pagetransformer corresponds to Onclicklistener.

The difference is that the Onclicklistener onclick method is called when the button is clicked and passes the button as a parameter.

The Transformpage method of Pagetransformer is called when the Viewpager is dragged.

The following is an analysis of the two parameters of the Transformpage method:


View

When Viewpager is dragged, two pager are affected, that is, the pager1 that are currently displayed and the Pager2 that are visible after dragging. And this view parameter is one of these two. This is not like a button click Callback, click once to call back the onclick, but callback two times, two times the view parameters are Pager1 and Pager2, the second parameter passed position is also different.


Position: A picture to explain that I painted ugly you come to hit me

So Pagetransformer just tells us the state of the current drag Viewpager, moving a few percent. The animation effect also needs our own implementation, and we need the view parameter as the body of the animation, position as the parameters of the animation.

An official example is also the realization:

Viewpager.setpagetransformer (False, new Pagetransformer () {@Overridepublic void Transformpage (view view, float position) {int pagewidth = View.getwidth (), if (position <-1) {view.setalpha (0);} else if (position <= 0) {View.set Alpha (1-position); View.settranslationx (0); View.setscalex (1); View.setscaley (1);} else if (position <= 1) {View.setalpha (1-position); View.settranslationx (PageWidth *-position); float scalefactor = MI N_scale + (1-min_scale) * (1-math.abs (position)); View.setscalex (scalefactor); View.setscaley (scalefactor);} else {view.setalpha (0);}});

Note that less than or equal to 0 is the processing of the left pager (that is, pager1), and greater than 0 is the processing of the right pager (that is, pager2).


We can implement our custom animations by setting different transparency, displacement, scaling, etc. by the percentage of drag, and the reader can try to implement several of them by themselves.


At this time, the problem arises, your IDE like a frightened little chick to yell at you, so a line of red color like blood red the sunset.


Run off ...


Property animations are only available after API 3.0, so Setscalex These methods are not in the 11 version of the following APIs.


You can add a newapi note to ignore the error, so that in api11 and above can display the custom animation effect, in the following version can only show the default effect, it seems that this is good.


But I am not satisfied, I can not restrain my hunger and thirst.


So I thought of the famous animation compatibility library nine old androids.

Ok, import the library and modify the calling statement to the following style:

Viewhelper.setalpha (view, 1-position);


Ah, everything is so beautiful. Open the simulator for 2.3 and the moment to witness the miracle.

Open in ... Open in ... Open in ... Open in ...

Endure the impulse to smash the broken computer, start running, then start dragging, and then no more.


It's not working, Dad!!! or the default drag animation!!!


Don't panic, take a deep breath.


If there is a problem, check the official API description, Setpagetransformer method Description:

Note: Prior to Android 3.0 The property animation APIs did not exist. As a result, setting a pagetransformer prior to Android 3.0 (API one) would have no effect.

What about the pit daddy? This is, you know I call this must be to achieve the property animation, I have nothing to play with the tune.


Look at how it ignores the low version of this discriminated race:

public void Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) {if (Build.VERSION.SDK_INT >= {Final Boolean hastransformer = transformer! = null;final Boolean needspopulate = hastransformer! = (mpagetransf Ormer = null); Mpagetransformer = Transformer;setchildrendrawingorderenabledcompat (Hastransformer); if ( Hastransformer) {Mdrawingorder = Reversedrawingorder? Draw_order_reverse:draw_order_forward;} else {mdrawingorder = Draw_order_default;} if (needspopulate) populate ();}}

I go, tough enough, direct if judgment, less than 11 direct what do not do.

Here are our most concerned statements:

Mpagetransformer = transformer;

The transformer we set up is saved, and it is assumed that similar code will be executed when dragging:

if (mpagetransformer!=null) {mpagetransformer.transformpage (view,position);}


So now our key is to assign our transformer to Mpagetransformer.


OK, start trying.

First, you want to customize a viewpager, and override the Setpagetransformer method.


Then in the Setpagetransformer method add a judgment, if the API is less than 11, we handle, higher than 11, to the parent class processing.


Our deal is to make the statement Mpagetransformer = Transformer to execute, and Mpagetransformer already has a set method, according to the coding specification it should be declared private, we can not directly obtain its reference, a test is true.


We had to make a few other ways to do it with reflection.

HD Feed Code:

@Overridepublic void Setpagetransformer (Boolean reversedrawingorder, Pagetransformer transformer) {if ( Build.VERSION.SDK_INT <) {try {//Find Mpagetransformer variable, note to find Field field = This.getclass () in parent class Viewpager. Getsuperclass (). Getdeclaredfield ("Mpagetransformer");//Set Modify Permissions Field.setaccessible (TRUE);// This is equivalent to executing the statement Mpagetransformer = Transformer;field.set (this, transformer);} catch (Exception e) {e.printstacktrace ();}} else {Super.setpagetransformer (reversedrawingorder, transformer);}}

The layout of the Viewpager changed to our custom Animviewpager, with a very excited mood, run again. Bingo, it's a success. In fact, the above is truncated on the simulator of 2.3.

Because it is achieved through reflection, if the day Google suddenly convulsions to change the name of the variable, then we do not expire. Of course, this kind of thing happens very low probability, do not care too much.

End of this article


Demo download

Android Curious baby _07_viewpager Toggle Animation (compatible with low version)

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.