ViewPager and androidviewpager for Android animation Switching

Source: Internet
Author: User

ViewPager and androidviewpager for Android animation Switching

Programmers who have experience in development know this effect, that is, when we install a software for the first time, there is a usage description of the picture switching effect. How does it implement it? Let's take a look at it today. The difficulty coefficient is 1.0, which means you can learn it if you analyze it carefully. Let's start with this article.

In this article, I need to use ViewPager. The introduction of ViewPager will not be described in detail. There are many introductions about ViewPager on the Internet. You can learn about it on your own.

Before making the animation effect, we first implement an image switching effect.

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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >        <com.example.android_viewpager.ViewPager        android:id="@+id/viewPager"        android:layout_width="match_parent"        android:layout_height="match_parent">    </com.example.android_viewpager.ViewPager></RelativeLayout>

Our Activity:

Public class MainActivity extends Activity {private ViewPager mViewPager; // The int [] imageIds = {R. drawable. guide_image1, R. drawable. guide_image2, R. drawable. guide_image3 }; List <ImageView> listImager = new ArrayList <ImageView> (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mViewPager = (ViewPager) findViewById (R. id. viewPager); // call the mViewPager provided by the system. setAdapter (new PagerAdapter () {@ Override public void destroyItem (ViewGroup container, int position, Object object Object) {container. removeView (listImager. get (position) ;}@ Override public Object instantiateItem (ViewGroup container, int position) {ImageView imagerView = new ImageView (MainActivity. this); imagerView. setImageResource (imageIds [position]); imagerView. setScaleType (ScaleType. CENTER_CROP); // sets the style container. addView (imagerView); listImager. add (imagerView); return imagerView;} @ Override public boolean isViewFromObject (View arg0, Object arg1) {return arg0 = arg1;} @ Override public int getCount () {return imageIds. length ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

In this way, the effect of our simplest instructions has been completed. Next, let's take a look at how to add some cool effects for our switch effect?

First of all we think of is Google there is no such method for our encapsulation, the answer is yes, you can access Google Android API to learn more about the mechanism (http://developer.android.com/training/animation/screen-slide.html ). Next I will show you how to add an animation effect to ViewPager.

Call method:

mViewPager.setPageTransformer(true, new DepthPageTransformer());

DepthPageTransformer. java:

@TargetApi(Build.VERSION_CODES.HONEYCOMB)public class DepthPageTransformer implements ViewPager.PageTransformer {        private static final float MIN_SCALE = 0.75f;    @SuppressLint("NewApi")    public void transformPage(View view, float position) {        int pageWidth = view.getWidth();        if (position < -1) { // [-Infinity,-1)            // This page is 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            view.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 is way off-screen to the right.            view.setAlpha(0);        }    }}

For this code, you can simply take the official website. Now we have achieved the switching effect. You can test it.

Is there a problem that some of you have already found? Why are there no results at all? Yes, this is not the reason for your mistake. This is because our animation effects are all implemented through attribute animation, attribute animation is supported by Versions later than Android3.0, so you don't have to worry about it. You can use a later version to present it perfectly. Of course, if you feel that this effect is not ideal, the official website also provides us with an effect. You can perform the same operation.

For the problems mentioned above regarding unsupported versions earlier than 3.0, here I will provide you with an improvement method:

We optimized DepthPageTransformer. java:

@ TargetApi (Build. VERSION_CODES.HONEYCOMB) public class myDepthPageTransformer implements ViewPager. pageTransformer {private static final float MIN_SCALE = 0.75f;/** use ViewHelper to replace the view provided by the system * (non-Javadoc) * @ see android. support. v4.view. viewPager. pageTransformer * # transformPage (android. view. view, float) */@ SuppressLint ("NewApi") public void transformPage (View view, float position) {int pageWidth = view. getWidth (); if (position <-1) {// [-Infinity,-1) // This page is way off-screen to the left. // view. setAlpha (0); ViewHelper. setAlpha (view, 0);} else if (position <= 0) {// [-1, 0] // Use the default slide transition 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-Math. abs (position); // view. setScaleX (scaleFactor); ViewHelper. setScaleX (view, scaleFactor); // view. setScaleY (scaleFactor); ViewHelper. setScaleY (view, scaleFactor);} else {// (1, + Infinity] // This page is way off-screen to the right. // view. setAlpha (0); ViewHelper. setAlpha (view, 0 );}}}

In this way, we use ViewHelper to replace our attribute animation attributes to solve the problem that attribute animation is not supported by our moderators before version 3.0. When we run it, we found that Versions later than version 3.0 still have no effect, why? We open the source code of ViewPager and find that there is a judgment in it:

If (Build. VERSION. SDK_INT> = 11) // Android VERSION judgment

This is the culprit. When our version is lower than 3.0, our animation effect Code cannot be executed at all. To solve this problem, we need to write this class. Comment out the version judgments in setPageTransformer;

Public void setPageTransformer (boolean reverseDrawingOrder, ViewPager. PageTransformer transformer) {// if (Build. VERSION. SDK_INT> = 11) // judge the Android VERSION {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 ();}}

Then we need to change the layout file:

    <com.example.android_viewpager.ViewPagerCompate        android:id="@+id/viewPager"        android:layout_width="match_parent"        android:layout_height="match_parent">    </com.example.android_viewpager.ViewPagerCompate>

Then make some changes to MainActivity:

MViewPager = (ViewPagerCompate) findViewById (R. id. viewPager); // modify

In this way, the effect we just modified can be displayed in Versions later than 3.0. Is it amazing. Finally, I will introduce you to the following results:

Public class RotateDownPagetransformer implements ViewPager. pageTransformer {private static final float MAX_ROTATE = 20F; private static float ROTATE = 0F;/** Effect Analysis: * slide can be divided into position A> B *: 0.0>-1.0 * B position: 1.0> 0.0 * (non-Javadoc) * @ see android. support. v4.view. viewPager. pageTransformer # * transformPage (android. view. view, float) * // @ Override public void transformPage (View view, float position) {int pageWidth = view. getWidth (); if (position <-1) {// [-Infinity,-1) ViewHelper. setAlpha (view, 0); // set transparency} else if (position <= 0) {// A page position: 0.0> 1.0 // calculates the Rotation Angle ROTATE = MAX_ROTATE * position; // sets the rotation center ViewHelper. setmediatx (view, pageWidth/2); ViewHelper. setpolicty (view, view. getMeasuredHeight (); // sets the select angle ViewHelper. setRotation (view, ROTATE);} else if (position <= 1) {// B page position: 1.0> 0.0 // calculates the Rotation Angle ROTATE = MAX_ROTATE * position; // sets the rotation center ViewHelper. setmediatx (view, pageWidth/2); ViewHelper. setpolicty (view, view. getMeasuredHeight (); // sets the select angle ViewHelper. setRotation (view, ROTATE);} else {// (1, + Infinity] ViewHelper. setAlpha (view, 0 );}}}

This is similar to the slice switching effect. Now, we have already introduced the ViewPager switching animation. There are a lot of content. If you have any questions, please leave a message.

 

Related Article

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.